Comparing 2 columns of two Python Pandas dataframes and getting the common rows

前端 未结 4 972
旧巷少年郎
旧巷少年郎 2020-12-03 18:43

I have 2 Dataframe as follows:

DF1=
    A    B   C    D
0   AA   BA  KK   0
1   AD   BD  LL   0
2   AF   BF  MM   0

DF2=
    K    L
0   AA   BA
1   AD   BF
         


        
4条回答
  •  有刺的猬
    2020-12-03 19:42

    This would be easier if you renamed the columns of df2 and then you can compare row-wise:

    In [35]:
    
    df2.columns = ['A', 'B']
    df2
    Out[35]:
        A   B
    0  AA  BA
    1  AD  BF
    2  AF  BF
    In [38]:
    
    df1['D'] = (df1[['A', 'B']] == df2).all(axis=1).astype(int)
    df1
    Out[38]:
        A   B   C  D
    0  AA  BA  KK  1
    1  AD  BD  LL  0
    2  AF  BF  MM  1
    

提交回复
热议问题