【问题标题】:Merging two DataFrames合并两个 DataFrame
【发布时间】:2016-10-24 10:33:31
【问题描述】:

我有 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

但我有点糊涂了。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    使用 to_frame() 或更新你的熊猫;

    在新的 pandas 版本中接受使用 Dataframe 加入系列

    【讨论】:

      【解决方案2】:

      错误消息表明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

      【讨论】:

      • 可能必须转换框架以匹配列。例如a1 = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]a2 = [['10', '1.2', '4.2'], ['1', '0', '0.06'], ['6', '4', '3']]df1 = pd.DataFrame(a1, columns=['one', 'two', 'three'])df2 = pd.DataFrame(a2, columns=['one', 'two', 'three'])pd.merge(df1, df2.loc[0].to_frame().T, on=['one', 'one'], how='inner')
      【解决方案3】:

      您可以简单地将 df2(它是一个系列,而不是数据帧)添加为一个新列

      df['price']=df2
      

      【讨论】:

        【解决方案4】:

        此错误表示您的对象之一不是熊猫数据框。

        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
        

        【讨论】:

          猜你喜欢
          • 2022-11-10
          • 2018-05-22
          • 2019-05-22
          • 2021-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-15
          • 1970-01-01
          相关资源
          最近更新 更多