在python中比较两个数据框

时间:2019-06-26 11:15:28

标签: python pandas dataframe

我有两个数据帧。我必须比较两个数据帧并使用python获取不匹配数据的位置。

注意: 第一栏永远不会是唯一的。

数据帧1:

   0         1   2                          3        4
0  1     Dhoni  24  Kota                       60000.0
1  2     Raina  90  Delhi                      41500.0
2  3     Kholi  67  Ahmedabad                  20000.0
3  4    Ashwin  45  Bhopal                      8500.0
4  5    Watson  64  Mumbai                      6500.0
5  6  KL Rahul  19  Indore                      4500.0
6  7    Hardik  24  Bengaluru                   1000.0

数据框2

   0         1   2                          3        4
0  3     Kholi  67  Ahmedabad                  20000.0
1  7    Hardik  24  Bengaluru                   1000.0
2  4    Ashwin  45  Bhopal                      8500.0
3  2     Raina  90  Delhi                      41500.0
4  6  KL Rahul  19  Chennai                    4500.0
5  1     Dhoni  24  Kota                       60000.0
6  5    Watson  64  Mumbai                      6500.0

我希望输出(3,5)-(Indore - Chennai)

1 个答案:

答案 0 :(得分:0)

df1=pd.DataFrame({'A':['Dhoni','Raina','KL Rahul'],'B':[24,90,67],'C':['Kota','Delhi','Indore'],'D':[6000.0,41500.0,4500.0]})
df2=pd.DataFrame({'A':['Dhoni','Raina','KL Rahul'],'B':[24,90,67],'C':['Kota','Delhi','Chennai'],'D':[6000.0,41500.0,4500.0]})

df1['df']='df1'
df2['df']='df2'
df=pd.concat([df1,df2],sort=False).drop_duplicates(subset=['A','B','C','D'],keep=False)

print(df)
          A   B        C       D   df
2  KL Rahul  67   Indore  4500.0  df1
2  KL Rahul  67  Chennai  4500.0  df2

我添加了df列进行显示,df的差异来自于其中