![](/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.