如何计算 NumPy bool 数组中真实元素的数量 [英] How to count the number of true elements in a NumPy bool array
本文介绍了如何计算 NumPy bool 数组中真实元素的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个布尔类型的 NumPy 数组boolarr".我想计算值为 True
的元素的数量.是否有专用于此任务的 NumPy 或 Python 例程?或者,我是否需要遍历脚本中的元素?
解决方案
您有多种选择.以下是两个选项.
boolarr.sum()numpy.count_nonzero(boolarr)
这是一个例子:
<预><代码>>>>将 numpy 导入为 np>>>boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)>>>布尔值数组([[假,假,真],[真,假,真],[真,假,真]],dtype=bool)>>>boolarr.sum()5当然,这是一个 bool
特定的答案.更一般地,您可以使用 numpy.count_nonzero
.
I have a NumPy array 'boolarr' of boolean type. I want to count the number of elements whose values are True
. Is there a NumPy or Python routine dedicated for this task? Or, do I need to iterate over the elements in my script?
解决方案
You have multiple options. Two options are the following.
boolarr.sum()
numpy.count_nonzero(boolarr)
Here's an example:
>>> import numpy as np
>>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
>>> boolarr
array([[False, False, True],
[ True, False, True],
[ True, False, True]], dtype=bool)
>>> boolarr.sum()
5
Of course, that is a bool
-specific answer. More generally, you can use numpy.count_nonzero
.
>>> np.count_nonzero(boolarr)
5
这篇关于如何计算 NumPy bool 数组中真实元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文