首页 > 解决方案 > 返回具有相同索引但值不同的数据

问题描述

我有一个数据框:

name country gender
John CA      1
John DA      0
John SA      1
Wang DA      1
Liu  SA      0
Zhang SA     0
Zhang DA     1

我希望返回具有相同名称但分配两个性别值的行。如果一个名字同时分配了性别 0 和 1,我们返回它们。

The returned frame is
John CA      1
John DA      0
John SA      1 
Zhang SA     0
Zhang DA     1

我用过groupby(['name', 'country'])['gender'].unique() 但它返回

John CA [0,1]

无论如何我可以退回框架吗?

标签: pythonpandas

解决方案


试试这个,谢谢@ShubhamSharma建议DataFrameGroupBy.nunique

count_ = df.groupby('name').gender.transform('nunique')

0    3
1    3
2    3
3    1
4    1
5    2
6    2
Name: gender, dtype: int64

mask = count_.gt(1) # create mask with count greater than 1

0     True
1     True
2     True
3    False
4    False
5     True
6     True
Name: gender, dtype: bool

print(df[mask])

    name country  gender
0   John      CA       1
1   John      DA       0
2   John      SA       1
5  Zhang      SA       0
6  Zhang      DA       1

推荐阅读