在 Pandas 中选择具有相同 ID 但不同值的行

4

我知道在数据库软件中这是可能的,但在Python Pandas中有没有任何方法可以做到呢?

ID1         ID2      Value
1209345     1203     2
1209345     1204     3 <-----
1209345     1205     4
1209345     1203     2
1209345     1204     7 <-----
1209346     1203     1
1209347     1204     5

我有一个ID1,相应地,我有多个ID2与一个值映射。我需要找到所有ID1ID2匹配但值不同的条目。
我的当前代码计算ID1ID2的唯一组合数量,但没有考虑每个组合的唯一Value
print(df.groupby(['ID1', 'ID2']).size())

ID1      ID2 
1209345  1203    2
         1204    2
         1205    1
1209346  1203    1
1209347  1204    1
dtype: int64

注意:这个问题是为@RohitGirdhar发布的,他已经删除了他的原始问题。我提供的解决方案不一定是唯一或最好的;鼓励其他答案。

2个回答

12

你可以使用nuniquetransform进行筛选:

df = df[df.groupby(['ID1', 'ID2'])['Value'].transform('nunique') > 1]

print (df)
       ID1   ID2  Value
1  1209345  1204      3
4  1209345  1204      7

1
一种方法是通过 groupbyset,过滤结果系列,然后通过 ID1ID2 的组合过滤原始数据框:
grps = df.groupby(['ID1', 'ID2'])['Value'].apply(set)
filtered = grps[grps.map(len) > 1].index

res = df[df.set_index(['ID1', 'ID2']).index.isin(filtered)]

print(res)

       ID1   ID2  Value
1  1209345  1204      3
4  1209345  1204      7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接