문제

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