问题描述
我可以看到我想通过concat
做的事情:在索引
I can see that what I'm trying to do is possible via concat
: Merge dataframes on index
为什么不能使用merge
做等效的事情?
Why can I not do something equivalent using merge
?
import pandas as pd
df = pd.DataFrame({'name':['joe strummer','johnny rotten'],'age':[73,80]})
df2 = pd.DataFrame({'name':['nancy','sid'],'age':[17,19]})
df.index.name = 'x'
df2.index.name = 'y'
pd.merge(df2,df, left_on='y',right_on='x')
推荐答案
这是可能的;只需使用left_index=True
代替left_on
,并使用right_index=True
代替right_on
:
This is possible; just use left_index=True
instead of left_on
, and right_index=True
instead of right_on
:
>>> pd.merge(df, df2, left_index=True, right_index=True)
age_x name_x age_y name_y
0 73 joe strummer 17 nancy
1 80 johnny rotten 19 sid
使用left_on
不起作用,因为索引是DataFrame列的单独对象.索引可以具有名称,甚至可以与您的某一列具有相同的名称,但是left_on
不会看到它,因为它仅查看列名称.
Using left_on
doesn't work because indexes are separate objects to DataFrame columns. An index can have name, even an identical name to one of your columns, but left_on
won't see it because it only looks at column names.
合并文档给出了这些论据的指导如下:
The documentation for merge gives the following guidance for these arguments:
使用左侧DataFrame中的索引作为连接键.如果它是一个MultiIndex,则另一个DataFrame中的键数(索引或列数)必须与级别数匹配
Use the index from the left DataFrame as the join key(s). If it is a MultiIndex, the number of keys in the other DataFrame (either the index or a number of columns) must match the number of levels
这篇关于根据索引列合并数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!