使用pandas合并时如何保持索引 [英] How to keep index when using pandas merge
本文介绍了使用pandas合并时如何保持索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想合并两个DataFrames
,并保留第一帧的索引作为合并数据集的索引.但是,当我进行合并时,生成的 DataFrame 具有整数索引.如何指定要保留左侧数据框中的索引?
I would like to merge two DataFrames
, and keep the index from the first frame as the index on the merged dataset. However, when I do the merge, the resulting DataFrame has integer index. How can I specify that I want to keep the index from the left data frame?
In [4]: a = pd.DataFrame({'col1': {'a': 1, 'b': 2, 'c': 3},
'to_merge_on': {'a': 1, 'b': 3, 'c': 4}})
In [5]: b = pd.DataFrame({'col2': {0: 1, 1: 2, 2: 3},
'to_merge_on': {0: 1, 1: 3, 2: 5}})
In [6]: a
Out[6]:
col1 to_merge_on
a 1 1
b 2 3
c 3 4
In [7]: b
Out[7]:
col2 to_merge_on
0 1 1
1 2 3
2 3 5
In [8]: a.merge(b, how='left')
Out[8]:
col1 to_merge_on col2
0 1 1 1.0
1 2 3 2.0
2 3 4 NaN
In [9]: _.index
Out[9]: Int64Index([0, 1, 2], dtype='int64')
切换到可以轻松复制的示例代码
Switched to example code that can be easily reproduced
推荐答案
In [5]: a.reset_index().merge(b, how="left").set_index('index')
Out[5]:
col1 to_merge_on col2
index
a 1 1 1
b 2 3 2
c 3 4 NaN
请注意,对于某些左合并操作,当 a
和 b
之间存在多个匹配项时,您可能会得到比 a
中更多的行>.在这种情况下,您可能需要删除重复项.
Note that for some left merge operations, you may end up with more rows than in a
when there are multiple matches between a
and b
. In this case, you may need to drop duplicates.
这篇关于使用pandas合并时如何保持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文