是否有一个 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/