获取numpy数组中非零元素的数量? [英] Get the number of nonzero elements in a numpy array?

查看:1560
本文介绍了获取numpy数组中非零元素的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能获得numpy数组中非零元素的长度,而无需遍历数组或对数组进行遮罩.速度是计算长度的主要目标.

Is it possible to get the length of the nonzero elements in a numpy array without iterating over the array or masking the array. Speed is the main goal of calculating the length.

本质上,类似于len(array).where(array != 0).

如果更改答案,则每一行都将从零开始.数组在对角线上用零填充.

If it changes the answer, each row will begin with zeros. The array is filled on the diagonal with zeros.

推荐答案

假设您的意思是非零元素的总数(而不是非零行的总数):

Assuming you mean total number of nonzero elements (and not total number of nonzero rows):

In [12]: a = np.random.randint(0, 3, size=(100,100))

In [13]: timeit len(a.nonzero()[0])
1000 loops, best of 3: 306 us per loop

In [14]: timeit (a != 0).sum()
10000 loops, best of 3: 46 us per loop

甚至更好:

In [22]: timeit np.count_nonzero(a)
10000 loops, best of 3: 39 us per loop

最后一个count_nonzero似乎在数组较小时也表现良好,而sum技巧就不那么多了:

This last one, count_nonzero, seems to behave well when the array is small, too, whereas the sum trick not so much:

In [33]: a = np.random.randint(0, 3, size=(10,10))

In [34]: timeit len(a.nonzero()[0])
100000 loops, best of 3: 6.18 us per loop

In [35]: timeit (a != 0).sum()
100000 loops, best of 3: 13.5 us per loop

In [36]: timeit np.count_nonzero(a)
1000000 loops, best of 3: 686 ns per loop

这篇关于获取numpy数组中非零元素的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆