Python 在索引列上合并吗?

Python 在索引列上合并吗?,python,pandas,Python,Pandas,因此,如果一个数据帧中的索引列与第二个数据帧中的另一列同名,panda无法合并?尝试重置索引: In [88]: c Out[88]: Address Name CustomerID 10 Address for Mike Mike 11 Address for Marcia Marcia In [89]: c.index Out[89]

因此,如果一个数据帧中的索引列与第二个数据帧中的另一列同名,panda无法合并?

尝试重置索引:

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

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

c.reset_index().merge(orders)
另外,请阅读您的文件。
希望这会有所帮助。

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

c.merge(orders, left_index=True, right_on='CustomID')
或者,此
合并将得到相同的结果。在这里,您加入了
c
(左侧数据框)的索引和右侧数据框中的
CustomerID
列。确保指定
how='left'
仅将右数据帧中的项目连接到左侧的所有记录(保留与
c
长度匹配的相等行数)。
merge
的默认行为是内部联接,其中结果仅包括在
orders
中找到匹配项的
c
记录(尽管这可能是您想要的结果)


thx,我现在正在读各种各样的书,很多信息:)谢谢Rojeer!
# 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
c.merge(orders, left_index=True, right_on='CustomerID', how='left')