numpy.count_nonzero是用于统计数组中非零元素的个数
详细用法: numpy.count_nonzero(a, axis=None, *, keepdims=False)
a: 为需要统计数组名
axis: 为统计的轴,当axis=0时统计数组y轴(每列) 非零元素个数,当axis=1时统计数组每 x轴(每行) 非零元素个数, 另外,axis可以为元组
具体还是看下例子帮助理解下吧
一个栗子:
import numpy as np
a = np.zeros((3,4))
print(np.count_nonzero(a))
'''
0
'''
b = np.eye(4)
print(np.count_nonzero(b))
'''
4
'''
c = np.array([[1,2,0],[0,1,0]])
print(c)
'''
[[1 2 0]
[0 1 0]]
'''
print(np.count_nonzero(c,axis=0))
'''
[1 2 0]
'''
print(np.count_nonzero(c,axis=1))
'''
[2 1]
'''
d = np.array([[[1,2,1],[0,1,2],[0,2,3],[0,2,3]],[[1,2,1],[0,1,2],[0,2,3],[0,2,3]]])
print(d)
'''
[[[1 2 1]
[0 1 2]
[0 2 3]
[0 2 3]]
[[1 2 1]
[0 1 2]
[0 2 3]
[0 2 3]]]
'''
print(np.count_nonzero(d,axis=0))
'''
[[2 2 2]
[0 2 2]
[0 2 2]
[0 2 2]]
'''
print(np.count_nonzero(d,axis=1))
'''
[[1 4 4]
[1 4 4]]
'''
print(np.count_nonzero(d,axis=(0,1))) #[2 8 8]
print(np.count_nonzero(d,axis=(0,1,2))) #18
希望这个例子可以便于大家理解,上面还有个keepdims,我也不是很清楚这是啥,需要了解的可以看下官网
官网直达链接:numpy.count_nonzero