pythonbool类型数组生成_Python Numpy:如何计算bool数组中真正元素的数量
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.
numpy.sum(boolarr)
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)
>>> np.sum(boolarr)
5
Of course, that is a bool-specific answer. More generally, you can use numpy.count_nonzero.
>>> np.count_nonzero(boolarr)
5
總結
以上是生活随笔為你收集整理的pythonbool类型数组生成_Python Numpy:如何计算bool数组中真正元素的数量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql行列转换_Excel、SQL、
- 下一篇: 十进制转十六进制_汇编语言 输入一位十六