Вопрос

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?

Это было полезно?

Решение

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.]])
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top