简体   繁体   English

计算二维numpy数组中的零行

[英]Count zero rows in 2D numpy array

How do you count the amount of zero rows of a numpy array? 您如何计算numpy数组的零行数量?

array = np.asarray([[1,1],[0,0],[1,1],[0,0],[0,0]])

-> has three rows with all zero's, hence should give 3 ->具有三全为零的行,因此应给3

Took me sometime to figure out this one and also couldn't find an answer on SO 花了我一段时间找出这一点,也找不到答案

You could also leverage the "truthiness" of non-zero values in an array. 您还可以利用数组中非零值的“真实性”。

np.sum(~array.any(1))

ie, sum the rows where none of the values in said row are truthy (and hence are all zero) 即,对行中的所有值都不为真(因此全为零)的行求和

You can use np.all if you're sure that the rows will have all zeros. 如果确定行将全为零,则可以使用np.all

 # number of rows which has non-zero elements
In [33]: sum(np.all(arr, axis=1))
Out[33]: 2

# invert the mask to get number of rows which has all zero as its elements
In [34]: sum(~np.all(arr, axis=1))
Out[34]: 3
import numpy as np

array = np.array([[1,1],[0,0],[1,1],[0,0],[0,0]])

non_zero_rows = np.count_nonzero((array != 0).sum(1))   # gives 2
zero_rows = len(array) - non_zero_rows                  # gives 3

Any better solutions? 有更好的解决方案吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM