2017-04-06 45 views
1

我有兩個熊貓數據框,df1和df2。我想創建一個數據框df3,其中包含使用df1中的一列和df2中的一列的所有組合。低效這樣做的僞代碼將是這樣的:在兩個維度上創建兩個熊貓數據框的組合

df3 = [] 
for i in df1: 
    for j in df2: 
     df3.append(i + j) # where i + j is the row with the combined cols from df1 and df2 

下面是DF1格式:

df1_id other_data_1 other_data_2 
1   0    1 
2   1    5 

DF2:

df2_id other_data_3 other_data_4 
1   0    1 
3   2    2 

而且目標是讓這個輸出 df3:

df1_id df2_id other_data_1 other_data_2 other_data_3 other_data_4 
1   1   0    1    0    1 
1   3   0    1    2    2 
2   1   1    5    0    1 
2   3   1    5    2    2 

回答

3

設置一個公共密鑰兩個dataframes之間,並使用pd.merge

df1['key'] = 1 
df2['key'] = 1 

合併和刪除鍵列:

df3 = pd.merge(df1,df2,on='key').drop('key',axis=1) 
df3 

輸出:

df1_id other_data_1 other_data_2 df2_id other_data_3 other_data_4 
0  1    0    1  1    0    1 
1  1    0    1  3    2    2 
2  2    1    5  1    0    1 
3  2    1    5  3    2    2 
+0

大,謝謝! –

+0

不客氣。 –