2016-06-22 204 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