python - Numpy 查找二维数组中出现的次数

标签 python numpy

是否有一个 numpy 函数来计算某个值在 2D numpy 数组中出现的次数。例如

np.random.random((3,3))

array([[ 0.68878371,  0.2511641 ,  0.05677177],
       [ 0.97784099,  0.96051717,  0.83723156],
       [ 0.49460617,  0.24623311,  0.86396798]])

如何找到 0.83723156 在此数组中出现的次数?

最佳答案

arr = np.random.random((3,3))
# find the number of elements that get really close to 1.0
condition = arr == 0.83723156
# count the elements
np.count_nonzero(condition)

condition 的值是一个 bool 值列表,表示数组的每个元素是否满足条件。 np.count_nonzero 计算数组中有多少个非零元素。对于 bool 值,它计算具有 True 值的元素的数量。

为了能够处理浮点精度,您可以改为执行以下操作:

condition = np.fabs(arr - 0.83723156) < 0.001

关于python - Numpy 查找二维数组中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38227751/

相关文章:

python - 检查列表元素接近什么值的最佳方法是什么?

python - 按表示相同值的多个键对字典进行排序

arrays - 数组的转换产生一个空占位符

python - 数据类型。 Python 中 S1 和 S2 的区别

python - Pandas 改进

python - 按相关对象的第一个实例对对象进行排序,Django

python - 同时求和 4 维矩阵的 3 个维度

python - Keras:训练时出现值错误

python - 查找所有重叠的字典键组

python - python中的过程矩阵