import pandas as pd
dt = {'order_id': ['A','A','B','B','B','C'], 'XY_ID': [4,5,4,5,6,4]}
print(pd.DataFrame(data=dt))
| order_id | XY_ID |
|---|---|
| 一個 | 4 |
| 一個 | 5 |
| 乙 | 4 |
| 乙 | 5 |
| 乙 | 6 |
| C | 4 |
我希望通過如下輸出將 Col2 中的所有兩個唯一元組分組并計算與它們關聯的 Col1 的數量
對于 4,5 對 A->4,B->4, A->5,B->5 計數為 2,因為通過 4 有 2 個公共關系,
對于 5,6 對 A->5, B-> 5 B->6 計數為 1,因為通過 5 有 1 個公共關系
| XY_ID_Tuple_IDX1 | XY_ID_Tuple_ID2 | 訂單數 |
|---|---|---|
| 4 | 5 | 2 |
| 5 | 6 | 1 |
| 4 | 6 | 1 |
我試過df.groupby(['col1', 'col2']).size().reset_index(name='count')和 pivot_table()
uj5u.com熱心網友回復:
這是一種使用方法itertools.combinations:
from itertools import combinations
s = (df.groupby('order_id')['XY_ID']
.agg(lambda x: list(combinations(x, 2)))
.explode()
)
out = s.groupby(s).count()
輸出:
XY_ID
(4, 5) 2
(4, 6) 1
(5, 6) 1
Name: XY_ID, dtype: int64
提供格式:
# code above
idx = pd.MultiIndex.from_tuples(out.index,
names=['XY_ID_Tuple_IDX1', 'XY_ID_Tuple_IDX2'])
out2 = out.to_frame('order_id').set_axis(idx).reset_index()
輸出:
XY_ID_Tuple_IDX1 XY_ID_Tuple_IDX2 order_id
0 4 5 2
1 4 6 1
2 5 6 1
uj5u.com熱心網友回復:
訣竅是將資料框與自身連接起來:
counts = (df.merge(df, on='order_id')
.groupby(['XY_ID_x', 'XY_ID_y'])
.count()
.reset_index()
)
counts.loc[counts['XY_ID_x'] < counts['XY_ID_y']]
counts內容:
XY_ID_x XY_ID_y order_id
1 4 5 2
2 4 6 1
5 5 6 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/488314.html
