Pandas DataFrame行匹配

时间:2014-06-20 04:56:56

标签: python pandas

我有两个数据框,并试图找到以下两个问题的解决方案。

  1. 我想匹配" Serial_Number"从df_old到df_new,想看看它们是否存在于df_old中。例如,如果df_old的Serial_Number为1,2,3且df_new的序列号为1,3,4则结果应为1和3.

  2. 显示数据的好方法。

    import pandas as pd
    
    df_old = pd.DataFrame({'S_No' : [1,2,3,4,5], 'Serial_Number' : [1234,2345,3456,1456,9867], 'Beg_Balance' : [10,20,45,21,29], 'End_Balance' : [2,6,8,5,3]})
    
    df_new = pd.DataFrame({'S_No' : [1,2,3,4], 'Serial_Number' : [8754,5657,1234,9867], 'Beg_Balance' : [32,20,10,29], 'End_Balance' : [5,6,2,1]})
    
    
    df_old_1 =  df_old.sort('Serial_Number',ascending=True)
    
    df_new_1 =  df_new.sort('Serial_Number',ascending=True)
    
    print df_old_1
    
    print df_new_1
    
    an = df_old_1['Serial_Number'] != df_new_1['Serial_Number']
    
    bn = df_new_1['Serial_Number'] != df_old_1['Serial_Number']
    

1 个答案:

答案 0 :(得分:1)

可能是你正在寻找某种合并:

In [11]: pd.merge(df_old_1, df_new_1, on='Serial_Number')
Out[11]:
   Beg_Balance_x  End_Balance_x  S_No_x  Serial_Number  Beg_Balance_y  End_Balance_y  S_No_y
0             10              2       1           1234             10              2       3
1             29              3       5           9867             29              1       4

the docs中查看更多内容。