[英]How to count occurrence of each unique ID in each bin in a 2D histogram (python or pandas)
我有一個 csv 文件,我想創建一個二維直方圖,其中每個 bin 中的值取決於唯一 ID。 例如(見下文),對於范圍 0<x<1 和 1<y<2,值是 2 (A, B) 而不是 3 (A, A, B),因為 A 出現了兩次。 謝謝!
ID | X | 是的 |
---|---|---|
一個 | 0.5 | 1.4 |
一個 | 0.6 | 1.6 |
一個 | 1.2 | 2.2 |
乙 | 0.7 | 1.7 |
C | 4.4 | 3.5 |
C | 3.1 | 3.7 |
i_x < x < j_x
, i_y < y < j_y
的 bin 可以唯一標識為(i_x, i_y)
; 我們可以看到這個元組對於每個 bin 都是唯一的。 i_x
和i_y
只是x
和y
的底值。 就像對於行: (x, y) = (0.5, 1.4)
bin 是: 0 < 0.5 < 1
, 1 < 1.4 < 1.2
這里i_x = 0 = floor(0.5)
和i_y = 1 = floor(1.4)
。
方法:
i_x
和i_y
。(i_x, i_y)
對 dataframe 進行分組,並計算每個組中的唯一IDs
。代碼:
>>> df
ID x y
0 A 0.5 1.4
1 A 0.6 1.6
2 A 1.2 2.2
3 B 0.7 1.7
4 C 4.4 3.5
5 C 3.1 3.7
df['bin_x'] = np.floor(df.x).astype(int)
df['bin_y'] = np.floor(df.y).astype(int)
df = (df.groupby(['bin_x', 'bin_y'], as_index = False)['ID']
.agg({'cnt' : 'nunique'}))
>>> df
bin_x bin_y cnt
0 0 1 2
1 1 2 1
2 3 3 1
3 4 3 1
如果您將直方圖定義為大小為 (5, 5) 的 numpy 數組,那么我們可以將cnt
值分配給該數組並獲得所需的直方圖。
histogram = np.zeros((5, 5))
histogram[df.bin_x, df.bin_y] = df.cnt
>>> histogram
array([[0., 2., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 1., 0.]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.