![](/img/trans.png)
[英]How to count occurrence of each unique ID in each bin in a 2D histogram (python or pandas)
[英]How to count the number of times a value is in a bin of a 2d histogram in python?
有没有一种方法可以用来计算单个值(例如 1)出现在加权二维直方图的每个 bin 中的次数? 我有一个使用 np.histogram2d(x, y, weight=weight, bins=45) 创建的加权二维直方图。
我知道我可以使用 (counts, _, _) = np.histogram2d(x, y, bins=45) 之类的东西来查看每个 bin 中值的总数,然后我可以通过执行 np 查看加权计数.histogram2d(x, y, weight=weight, bins=45)。 但是,通过加权直方图,我想查看默认值 '1' 在 45 个 bin 中的每一个中出现了多少次。 有没有一种简单的方法可以做到这一点?
您可以使用np.unique()
(将return_counts
标志设置为True
)来计算出现在数组上的每个单独值的出现次数,或者您可以使用np.count_nonzero()
和相等比较的组合数组,例如:
np.unique()
:import numpy as np
np.random.seed(0) # make sure the example is reproducible
arr = np.random.randint(0, 10, 1000)
values, counts = np.unique(arr, return_counts=True)
print(values)
# [0 1 2 3 4 5 6 7 8 9]
print(counts)
# [ 99 96 97 122 99 105 94 97 95 96]
np.count_nonzero()
import numpy as np
np.random.seed(0) # make sure the example is reproducible
arr = np.random.randint(0, 10, 1000)
print(np.count_nonzero(arr == 1))
# 96
您无法从np.histogram()
或np.histogram2d()
的结果中检索相同的信息,根据定义,它们是聚合结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.