[英]Pandas groupby two columns and count shared values in third
在 Pandas 中,我想對兩列進行分組並計算共享的第三列值的數量。 隨着對更大共享的偏好的增加。
在下面的 dataframe 中,對 col1 值進行分組,對 col2 值進行分組,並計算 col2 值共享 col3 值的頻率。
結果是:ID1 和 ID2 共享一個 col3 值 (2)。 ID3 與 none (1) 共享。 但是,ID1、ID2 和 ID4 也共享一個值 (3)。 由於 ID1 和 ID2 已經共享一個值,因此采用兩個 ID 和更多 ID 共享的值 (3)。 因此答案是3,1。 計數列表必須始終 = 唯一的 col2 值。
col1 | 列2 | 列3 |
---|---|---|
一種 | ID1 | 15 |
一種 | ID1 | 16 |
一種 | ID1 | 12 |
一種 | ID2 | 15 |
一種 | ID2 | 12 |
一種 | ID3 | 18 |
一種 | ID4 | 19 |
一種 | ID4 | 12 |
如果我對你的理解正確,我想你想按col3
而不是col2
分組:
df = pd.read_html('https://stackoverflow.com/q/69419264/14277722')[0]
df = df.groupby(['col1','col3'])['col2'].apply(list).reset_index()
df['count'] = df['col2'].apply(len)
然后,您可以刪除col2
是另一行的子集的行,其中包含以下內容:
arr = pd.get_dummies(df['col2'].explode()).max(level=0).to_numpy()
subsets = np.matmul(arr, arr.T)
np.fill_diagonal(subsets, 0)
mask = ~np.equal(subsets, np.sum(arr, 1)).any(0)
df = df[mask]
col1 col3 col2 count
0 A 12 [ID1, ID2, ID4] 3
3 A 18 [ID3] 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.