pandas - 如何按两行比较值
问题描述
如何选择列 [nbr] 包含不同值的行。
可能某些 [st_id] 只有一条记录。
st_id trc dir nbr
88900 4009114 1 2
88900 4009114 2 2
88000 4009115 1 2
88000 4009115 2 2
88300 4009113 1 3
88300 4009113 2 2
88400 4009110 1 4
88500 5120012 1 1
88500 5120013 2 2
88600 1270081 1 3
结果:
st_id trc dir nbr
88300 4009113 1 3
88300 4009113 2 2
88500 5120012 1 1
88500 5120013 2 2
解决方案
您可以首先使用drop_duplicates
为每对获取一行st_id, nbr
,然后groupby
仅st_id
用于查找存在多个实例的实例nbr
:
(df
.drop_duplicates(["st_id", "nbr"])
.groupby(["st_id"])
.filter(lambda x: x.nbr.nunique() > 1)
)
st_id trc dir nbr
0 88300 4009114 1 2
4 88300 4009113 1 3
7 88500 5120012 1 1
8 88500 5120013 2 2
推荐阅读
- javascript - event.latLng returns latitude and longitude, however, I can't extract just lat or lng
- android - 如何在 Kotlin 中将两个数组与参数数组合并为一个数组?
- csv - 使用 java.io.FileOutputStream 导出 .csv
- scala - 为什么 Scala Map 上的 .map.flatten 和 flatMap 返回不同的结果?
- azure - Azure Runbook to connect to SQL server running on Azure VM
- c# - Global Function in Asp.net
- ios - Status bar not sticking to top on Some iPads
- angular - @Input/@Output check in templates
- ios - How to Merge video with audio?
- javascript - Function run function