2017-07-17 63 views
1

我有兩個dataframes:如何使用多列合併兩個數據框?

df_1 = pd.DataFrame(columns=["pointid","lat","lon"],data=[[1,41.792145,3.046884],[2,41.799834,3.051082],[3,41.813694,3.063463], [4,41.817673,3.067025]]) 

df_2 = pd.DataFrame(columns=["id","point_from","point_to"], 
           data=[[1,1,2],[2,1,3],[3,2,3]]) 

我想,爲了得到一個新的數據框df_3有以下的列(1行的例子)來合併它們:

id point_from point_to lat_from lon_from lat_to  lon_to 
1  1    2   41.792145 3.046884 41.799834 3.051082 

我該怎麼做?

回答

1

一種選擇是在point_frompoint_to與df_2合併df_1兩次分別列:

df_1 = df_1.set_index("pointid") 

(df_2.merge(df_1.add_suffix("_from"), left_on="point_from", right_index=True) 
    .merge(df_1.add_suffix("_to"), left_on="point_to", right_index=True)) 

# id point_from point_to lat_from lon_from  lat_to lon_to 
#0 1   1   2 41.792145 3.046884 41.799834 3.051082 
#1 2   1   3 41.792145 3.046884 41.813694 3.063463 
#2 3   2   3 41.799834 3.051082 41.813694 3.063463 
相關問題