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

标签 python-2.7 pandas scikit-learn

我有两个数据框 - 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/

相关文章:

python - TypeError : expected httplib. 消息,得到 <type 'instance' >。在 GAE 上使用 requests.get(url) 时

python - Pandas 如何按间隔按列拆分数据帧

python - 当列数事先未知时如何访问 Pandas 数据框列

python - 从 scipy 导入 softmax 并在从 sklearn 导入后使用它时出现问题

python - keras:将 ImageDataGenerator 和 KFold 用于 fit_generator 的问题

python - 如何使用tensorflow进行文本分类?

python - 它说它不是安装了一个模块

土耳其语字符的python编码

python - 删除数据框中的特定字符

python - Pandas 通过元组重命名多索引的单行