2016-06-22 206 views
5

我有2 DataFrames我想要合併。我查看了文檔,並試圖執行以下操作,但對如何執行操作感到困惑。就像我說我有2個DataFrames合併兩個數據幀

df1: 

     id  name type currency 
0 BTA.S Applewood Hard  GBp 
1 VOD.S Softwood Soft  GBp 

df2: 

    id 
BTA.S 301.221525 
VOD.S 213.791400 

,我想回:

 id  name type currency  price 
0 BTA.S Applewood Hard  GBp 301.221525 
1 VOD.S Softwood Soft  GBp 213.791400 

凡從DF2價格列合併DF1。 (只是爲了讓你知道,我完成時會有更多的木材類型)。

我試圖這樣做的幾種方法:

Result = df1.merge(df2[['*.S']], left_on='id', right_index=True) 

在那裏我遇到了異常:

ValueError: can not merge DataFrame with instance of type <class 'pandas.core.series.Series'> 

Result = pd.concat([Df1, Df2], axis=1, ignore_index=True) 

在那裏我得到異常:

ValueError: labels ['type'] not contained in axis 

但我感到困惑。對不起,如果這是一個基本的問題。任何幫助將非常感激。非常感謝

回答

16

錯誤消息指示df2的類型爲pd.Series。你需要轉換df2.to_frame().merge()需要一個pd.DataFrame()輸入(see docs):

df1.merge(df2[['*.S']].to_frame(), left_on='id', right_index=True) 

,而你也可能只是可能:

df1.merge(df2.to_frame(), left_on='id', right_index=True) 

或者,你可以使用pd.DataFrame.join()它接受一個pd.Series

2

此錯誤表示您的一個對象是而不是是一個熊貓數據框。

ValueError: can not merge DataFrame with instance of type <class 'pandas.core.series.Series'> 

爲了證實這一點,

print(type(df2)) 

,並應輸出pandas.core.series.Series

實現你想要的結果,

df2 = df2.to_frame().reset_index() 
df2.columns = ['id', 'price'] 
df1.merge(df2) 

輸出:

id name type currency price 
0 BTA.S Applewood Hard GBp  301.221525 
1 VOD.S Softwood Soft GBp  213.791400 
1

您可以簡單地添加DF2(這是一個系列,而不是一個數據幀)作爲新列

df['price']=df2