[英]How to merge using index items with Pandas
I have two dataframes df_a and df_b. 我有两个数据框df_a和df_b。 Both dataframes have index with three items (id / sub_id / sort_id). 两个数据帧的索引都包含三个项目(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' 但是我有一个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): 由于您尝试合并索引,因此请指定left_index=True, right_index=True
,这是正确的,但随后您将无法指定left_on
或right_on
(信息是多余的,并且不被接受):
>>> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.