合并两个数据帧 [英] Merging two DataFrames

查看:52
本文介绍了合并两个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个 DataFrames 想要合并.我查看了文档并尝试执行以下操作,但对如何执行感到困惑.就像我说的,我有 2 个 DataFrames:

I have 2 DataFrames which I would like to merge. I have looked at the documentation and tried to perform the following operation but an getting confused as to how to do it. Like I said I have 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 中的 price 列与 df1 合并的地方.(只是为了让您知道在我完成时会有更多的木材类型).

Where the price column from the df2 is merged with df1. (Just to let you know there will be alot more wood types by the time I've finished).

我尝试了几种方法来做到这一点:

I have tried a few methods of doing this:

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

但我越来越糊涂了.

推荐答案

错误消息表明 df2pd.Series 类型.您需要将 df2 .to_frame() 转换为 .merge() 需要 pd.DataFrame() 输入(查看文档):

The error message indicates that df2 is of type pd.Series. You need to convert df2 .to_frame() as .merge() needs a pd.DataFrame() input (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.Seriespd.DataFrame.join().

Alternatively, you can use pd.DataFrame.join() which accepts a pd.Series.

这篇关于合并两个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆