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
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:
left_index : boolean, default False
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