numpy去除元素全为零的行或列

  1. np.all() 所有元素不为零或空或False,返回True
import numpy as np
a=np.array([0,1,2,0,3,4,0,5,6,0,0,0,0,0,0]).reshape(5,3)
#去除全零行
print(a[[not np.all(a[i] == 0) for i in range(a.shape[0])], :])
[[0 1 2]
 [0 3 4]
 [0 5 6]]
#去除全零列
print(a[:, [not np.all(a[:, i] == 0) for i in range(a.shape[1])]])
[[1 2]
 [3 4]
 [5 6]
 [0 0]
 [0 0]]
  1. 请注意某行或列元素是否存在和为零的情况。
import numpy as np
a=np.array([0,1,2,0,3,4,0,5,6,0,0,0,0,0,0]).reshape(5,3)

a
array([[0, 1, 2],
       [0, 3, 4],
       [0, 5, 6],
       [0, 0, 0],
       [0, 0, 0]])

#去除全零行
a[a.sum(axis=1)!=0,:]
array([[0, 1, 2],
       [0, 3, 4],
       [0, 5, 6]])

#去除全零列

a[:,a.sum(axis=0)!=0]
array([[1, 2],
       [3, 4],
       [5, 6],
       [0, 0],
       [0, 0]])

你可能感兴趣的:(numpy去除元素全为零的行或列)