【问题标题】:Pandas merge on index column? [duplicate]熊猫在索引列上合并? [复制]
【发布时间】:2018-02-03 23:33:06
【问题描述】:
In [88]: c
Out[88]: 
                       Address    Name
CustomerID                            
10            Address for Mike    Mike
11          Address for Marcia  Marcia

In [89]: c.index
Out[89]: Int64Index([10, 11], dtype='int64', name='CustomerID')

In [90]: orders
Out[90]: 
   CustomerID   OrderDate
0          10  2014-12-01
1          11  2014-12-01
2          10  2014-12-01

In [91]: orders.index
Out[91]: RangeIndex(start=0, stop=3, step=1)

In [92]: c.merge(orders)
---------------------------
MergeError: No common columns to perform merge on

如果一个dataframe中的index列与第二个dataframe中的另一列同名,那么panda就不能合并?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    尝试重置索引:

    c.reset_index().merge(orders)
    

    【讨论】:

      【解决方案2】:

      您需要明确指定如何加入表。默认情况下,merge 将选择常用列名作为合并键。对于您的情况,

      c.merge(orders, left_index=True, right_on='CustomID')
      

      另外,请阅读pandas.DataFrame.merge 的文档。 希望这会有所帮助。

      【讨论】:

      • 谢谢,我现在正在阅读各种书籍,很多信息 :) 谢谢 Rojeer!
      【解决方案3】:

      join 方法默认进行左连接(how='left') 并加入数据帧的索引。因此将orders 数据帧的索引设置为CustomerId 然后加入。

      # Create sample data.
      orders = pd.DataFrame(
          {'CustomerID': [10, 11, 10],
           'OrderDate': ['2014-12-01', '2014-12-01', '2014-12-01']})    
      c = pd.DataFrame(
          {'Address': ['Address for Mike', 'Address for Marcia'], 
           'Name': ['Mike', 'Marcia']},
          index=pd.Index([10, 11], dtype='int64', name='CustomerID'))
      
      # Join.
      >>> c.join(orders.set_index('CustomerID'))
                             Address    Name   OrderDate
      CustomerID                                        
      10            Address for Mike    Mike  2014-12-01
      10            Address for Mike    Mike  2014-12-01
      11          Address for Marcia  Marcia  2014-12-01
      

      或者,这个merge 会给你同样的结果。在这里,您将加入c(左侧数据框)的索引和右侧数据框中的CustomerID 列。确保指定 how='left' 仅将右侧数据框中的项目连接到左侧的所有记录(保留与 c 长度匹配的等效行数)。 merge 的默认行为是内连接,结果仅包括来自 c 且在 orders 中找到匹配项的记录(尽管这可能是您想要的结果)。

      c.merge(orders, left_index=True, right_on='CustomerID', how='left')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-01
        • 2018-06-17
        • 2021-07-31
        • 2018-02-02
        • 1970-01-01
        • 2016-08-01
        • 2015-02-01
        • 2020-04-05
        相关资源
        最近更新 更多