python - 返回具有相同索引但值不同的数据
问题描述
我有一个数据框:
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]
无论如何我可以退回框架吗?
解决方案
试试这个,谢谢@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
推荐阅读
- c# - 如何在 C# 和 Visual Studio 中获取数组的总和和平均值?
- algorithm - 我们可以在 O(n^2) 中进行 4-sum 算法吗?
- javascript - 如何在包含文本的 div/span 上插入假插入符号?
- docker - 更改 Solr 的 JVM 参数
- c# - 如果对象列表中不存在对象字段,则更新它?
- c# - Scrolling panel visual issue
- java - 从控制器 1 向控制器 2 发送消息
- reactjs - 如何将带有参数的 redux 操作分配给 onClick 属性?
- android - 如何在没有任何第三方库的情况下在 Android 上制作 RTSP 客户端?
- apache-spark - 在 Spark 中读取 ORC 文件时如何保留分区列