Pandas基于索引列合并?

5
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

如果一个数据框中的索引列与另一个数据框中的某一列具有相同的名称,则panda将无法合并这两个数据框吗?

3个回答

12

您需要明确指定如何连接表格。默认情况下,merge 将选择公共列名作为合并键。对于您的情况,

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

同时,请阅读pandas.DataFrame.merge文档,希望这会对你有所帮助。


1
谢谢,我现在正在阅读各种书籍,有很多信息 :) 谢谢 Rojeer! - DmitrySemenov

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 的默认行为是内部连接,其中结果仅包括在 orders 中找到匹配项的那些记录(尽管这可能是您想要的结果)。

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

1
尝试重置索引:
c.reset_index().merge(orders)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接