简体   繁体   中英

How to merge using index items with Pandas

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM