如何获取右数据帧中不在左数据帧中的数据

2024-04-20 11:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧,我试图输出的数据是在一个,但不是另一个。你知道吗

我可以得到第一个数据帧中的数据,但不能使用第二个数据帧

only_new = old.merge(
new, 'outer', on=['Employee ID', 'Benefit Plan Type'],
suffixes=['','_'], indicator=True
).query('_merge == "left_only"').reindex_axis(old.columns, axis=1)

下面是我用来获取第二个数据帧中的数据

only_new =new.merge(
old, 'outer', on=['Employee ID', 'Benefit Plan Type'],
suffixes=['','_'], indicator=True
).query('_merge == "left only"').reindex_axis(new.columns, axis=1)

但是它不返回任何数据,但是使用Excel我可以看到应该有几行。你知道吗

看来这应该管用

only_new = old.merge(new, on='Employee ID', indicator=True, how='outer',
       only_new[only_new['_merge'] == 'right_only'])

但我明白了

SyntaxError: non-keyword arg after keyword arg

Tags: 数据idtrueonlynewontypeemployee
2条回答

考虑数据帧oldnew

old = pd.DataFrame(dict(
        ID=[1, 2, 3, 4, 5],
        Type=list('AAABB'),
        Total=[9 for _ in range(5)],
        ArbitraryColumn=['blah' for _ in range(5)]
    ))

new = pd.DataFrame(dict(
        ID=[3, 4, 5, 6, 7],
        Type=list('ABBCC'),
        Total=[9 for _ in range(5)],
        ArbitraryColumn=['blah' for _ in range(5)]
    ))

然后取对称同一解

old.merge(
    new, 'outer', on=['ID', 'Type'],
    suffixes=['_', ''], indicator=True  # changed order of suffixes
).query('_merge == "right_only"').reindex_axis(new.columns, axis=1)
#                   \......../                 \./
#   changed from `left` to `right`      reindex with `new`

  ArbitraryColumn  ID  Total Type
5            blah   6    9.0    C
6            blah   7    9.0    C

似乎您需要将'_merge == "left_only"'更改为'_merge == "right_only"'。你知道吗

相关问题 更多 >