Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 如何删除Pandas中两个数据帧中的公用行?_Python 2.7_Pandas_Scikit Learn - Fatal编程技术网

Python 2.7 如何删除Pandas中两个数据帧中的公用行?

Python 2.7 如何删除Pandas中两个数据帧中的公用行?,python-2.7,pandas,scikit-learn,Python 2.7,Pandas,Scikit Learn,我有两个数据帧-df1和df2 df1 has row1,row2,row3,row4,row5 df2 has row2,row5 我想要一个新的数据帧,这样df1-df2。也就是说,结果数据帧的行应为-row1、row3、row4 您可以使用index.difference()函数 import numpy as np import pandas as pd df1 = pd.DataFrame(np.random.randn(5, 2), index= ['row' + str(i)

我有两个数据帧-
df1
df2

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

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

您可以使用
index.difference()
函数

import numpy as np
import pandas as pd

df1 = pd.DataFrame(np.random.randn(5, 2), index= ['row' + str(i) for i in range(1, 6)])
df1

        0             1
row1    0.249451    -0.107651
row2    1.295390    -1.773707
row3    -0.893647   -0.683306
row4    -1.090551   0.016833
row5    0.864612    0.369138

df2 = pd.DataFrame(np.random.randn(2, 2), index= ['row' + str(i) for i in [2, 5]])
df2

        0           1
row2    0.549396    -0.675574
row5    1.348785    0.942216

df1.loc[df1.index.difference(df2.index), ]

        0           1
row1    0.249451    -0.107651
row3    -0.893647   -0.683306
row4    -1.090551   0.016833
您可以使用将两个数据帧按行连接,然后使用删除其中所有重复的行

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

有关此类问题,请参见《左图加入熊猫》

这是最好的方法: 请注意,drop duplicated用于最小化比较。没有他们也行

为什么这是最好的方法? 最好的方法是比较行内容本身,而不是索引或一列/两列,相同的代码可用于其他筛选器,如“两者”和“仅限右”以获得类似的结果

  • index.difference仅适用于基于唯一索引的比较
  • pandas.concat()
    drop\u duplicated()
    结合使用并不理想,因为它还将删除可能仅位于您想要保留的数据帧中的行,并且这些行是出于正当理由而复制的

  • 注意,这并不比较两个数据帧的内容,它只是比较索引的值。其次,你应该回答这个问题。这属于评论。感谢您的反馈。我是新来的。
    df = df1.drop_duplicates().merge(df2.drop_duplicates(), on=df2.columns.to_list(), 
                       how='left', indicator=True)
    df.loc[df._merge=='left_only',df.columns!='_merge']