![](/img/trans.png)
[英]How to divide one column by another where one dataframe's column value corresponds to another dataframe's column's value in Python Pandas?
[英]How can I find all rows with a value in one column which corresponds to more than one value in another column in a pandas dataframe?
我需要找出 A 列中有多少值對應於 B 列中的多個值。
一個 | 乙 |
---|---|
1 | 貓 |
2 | 狗 |
3 | 鼠 |
1 | 馬 |
1 | 貓 |
2 | 鳥 |
3 | 鼠 |
我如何遍歷 A 中的所有值並獲得一個告訴我的輸出:
1 有貓和馬
2 有狗和鳥
如果您只想知道哪些值符合您的條件:
df.loc[~df.duplicated(keep=False), 'A'].unique()
輸出: array([2, 1])
要獲取值:
out = df.groupby('A')['B'].agg(set)
out = out[out.str.len()>1]
輸出:
A
1 {cat, horse}
2 {bird, dog}
Name: B, dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.