Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce a sparse matrix in numpy

It seems that I am missing something very basic here. I have a large square matrix which is mostly zeros. What I want is to reduce it to a matrix that contains all rows and columns with non-zero entries. For example:

1 1 0 1
1 1 0 1
0 0 0 0
1 1 0 1

Should be reduced to:

1 1 1
1 1 1
1 1 1

Is there a fast way to do this?

like image 511
ivan-k Avatar asked Apr 22 '26 14:04

ivan-k


1 Answers

How about something like this:

>>> arr
array([[ 1.,  1.,  0.,  1.],
       [ 1.,  1.,  0.,  1.],
       [ 0.,  0.,  0.,  0.],
       [ 1.,  1.,  0.,  1.]])

>>> mask = (arr==0)

arr = arr[~np.all(mask,axis=0)]
arr = arr[:,~np.all(mask,axis=1)]
>>> arr
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
like image 110
Daniel Avatar answered Apr 25 '26 17:04

Daniel