Domanda

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?

È stato utile?

Soluzione

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.]])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top