![](/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.