gpt4 book ai didi

python-2.7 - 如何在 Pandas 中删除两个数据框中的公共(public)行?

转载 作者:行者123 更新时间:2023-12-04 02:07:00 25 4
gpt4 key购买 nike

我有两个数据框 - df1df2 .

df1 has row1,row2,row3,row4,row5
df2 has row2,row5

我想要一个新的数据框,这样 df1-df2 .也就是说,结果数据帧的行应为 - row1,row3,row4 .

最佳答案

您可以使用 pandas.concat 按行连接两个数据帧,然后是 drop_duplicates 删除其中所有重复的行。

In [1]: import pandas as pd
df_1 = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df_2 = pd.DataFrame({"A":["foo", "bar", "foo", "bar"], "B":[1,0,1,0], "C":["A","B","A","B"]})

In [2]: df = pd.concat([df_1, df_2])

In [3]: df
Out[3]:
A B C
0 foo 0 A
1 foo 1 A
2 foo 1 B
3 bar 1 A
0 foo 1 A
1 bar 0 B
2 foo 1 A
3 bar 0 B

In [4]: df.drop_duplicates(keep=False)
Out[4]:
A B C
0 foo 0 A
2 foo 1 B
3 bar 1 A

关于python-2.7 - 如何在 Pandas 中删除两个数据框中的公共(public)行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38681340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com