我有一個資料集,我正在尋找是否有辦法根據 col 值匹配資料。
col-A col-B
Apple squash
Apple lettuce
Banana Carrot
Banana Carrot
Banana Carrot
dragon turnip
melon potato
melon potato
pear potato
匹配
- 如果 col A 匹配另一個 col a 而 col b 不匹配
- 如果 col B 匹配另一個 col B 而 col a 不匹配
col-A col-B
Apple squash
Apple lettuce
melon potato
melon potato
pear potato
編輯固定錯字
edit2 修正了第二個錯字
uj5u.com熱心網友回復:
所以,如果我理解得很好,你想選擇每一行,這樣 colA (resp. colB) 然后 colB (resp. colA) 的分組會導致多個組。
我可以建議:
grA = df2.groupby("colA").filter(lambda x : x.groupby("colB").ngroups > 1)
grB = df2.groupby("colB").filter(lambda x : x.groupby("colA").ngroups > 1)
導致 :
grA
colA colB
0 Apple squash
1 Apple lettuce
和
grB
colA colB
6 melon potato
7 melon potato
8 pear potato
合并兩個資料幀將導致所需的輸出。
uj5u.com熱心網友回復:
IIUC,您需要計算兩個掩碼來確定哪個組與其他值具有唯一匹配:
m1 = df.groupby('col-B')['col-A'].transform('nunique').gt(1)
m2 = df.groupby('col-A')['col-B'].transform('nunique').gt(1)
out = df[m1|m2]
輸出:
col-A col-B
0 Apple squash
1 Apple lettuce
6 melon potato
7 melon potato
8 pear potato
您還可以通過以下方式獲得唯一/獨家對:
df[~(m1|m2)]
col-A col-B
2 Banana Carrot
3 Banana Carrot
4 Banana Carrot
5 Pear Cabbage
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444396.html
上一篇:在串列中按字母順序對字典進行排序
