0

I have two dataframes df_a and df_b. Both dataframes have index with three items (id / sub_id / sort_id).

I would like to merge these two dataframes with index items.

** df_a **
                      | c1 | c2 | c3 | 
id | sub_id | sort_id |    |    |    | 
 1 |      1 |       3 |   a|   b|   c| 
 2 |      1 |       1 |   a|   b|   c| 
 3 |      1 |       2 |   a|   b|   c| 

** df_b **
                      | c1 | c2 | c3 | 
id | sub_id | sort_id |    |    |    | 
 1 |      1 |       3 |   x|   y|   z| 
 2 |      1 |       1 |   x|   y|   z| 
 3 |      1 |       2 |   x|   y|   z| 

However I had a KeyError: 'id'

df_merge = pd.merge(df_a, df_b, how='left', left_index=True, right_index=True, left_on=['id','sub_id','sort_id'], right_on=['id','sub_id','sort_id'])

How can I merge these two dataframes?

1 Answer 1

2

Since you are trying to merge on the index, you specify left_index=True, right_index=True, which is correct, but then you can't specify left_on or right_on (the information is redundant, and not accepted):

>>> pd.merge(df_a, df_b, left_index=True, right_index=True)
                  c1_x c2_x c3_x c1_y c2_y c3_y
id sub_id sort_id                              
1  1      3          a    b    c    x    y    z
2  1      1          a    b    c    x    y    z
3  1      2          a    b    c    x    y    z
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.