Ash*_*ton 1 python numpy where zero
我有代码:
def find_zeros(data):
'''creates a list of the indexes of the zeros in the data'''
zeroidx=np.where(np.any(data==0, axis=1))
print zeroidx
return len(zeroidx)
Run Code Online (Sandbox Code Playgroud)
但结果是:
(array([525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537,
538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550,
551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563,
564, 565], dtype=int64),)
Run Code Online (Sandbox Code Playgroud)
它给出了长度1.
如何找到数字数组的长度?
这会找到零的位置.基本上我只是想知道数据中有多少个零?还有更好的方法吗?
只需检查零值并在结果布尔数组上调用sum:
(data == 0).sum()
Run Code Online (Sandbox Code Playgroud)
这是一种更通用的解决方案,可用于查找数组中的任何值,而不仅仅是零和非零数字.
它甚至表现稍微但不显着count_nonzero(阵列长度为100000000):
%timeit (a == 0).sum()
1 loops, best of 3: 249 ms per loop
%timeit len(a) - numpy.count_nonzero(a)
1 loops, best of 3: 326 ms per loop
Run Code Online (Sandbox Code Playgroud)