我想合并两个如下所示的数据框:
In[14]: test1=pd.DataFrame({'col1':[1,2,3,
6,4,5],
'col2':['First','Second','Third',
'Sixth','Fourth','Fifth']})
test1
Out[14]:
col1 col2
0 1 First
1 2 Second
2 3 Third
3 6 Sixth
4 4 Fourth
5 5 Fifth
和
In[15]: test2=pd.DataFrame({'col1':[1,7,2,
3,4,5],
'col2':['First','Seventh','Second',
'Third','Fourth','Fifth']})
test2
Out[15]:
col1 col2
0 1 First
1 7 Seventh
2 2 Second
3 3 Third
4 4 Fourth
5 5 Fifth
正如您可能注意到的,这些 DataFrame 几乎相同,但每个 DataFrame 都有另一行中没有的额外行(test1
中的 3 6 Sixth
> 和 test2
中的 1 7 Seventh
)。
我想以这样一种方式合并这些 DataFrame,即一个 DataFrame 中的任何额外行都插入到另一个 DataFrame 中,尽可能靠近其原始位置。这是我希望得到的结果:
col1 col2
0 1 First
1 7 Seventh
2 2 Second
3 3 Third
4 6 Sixth
5 4 Fourth
6 5 Fifth
我尝试使用
In[16]: pd.merge(test1, test2, how='outer', sort=False)
此输出
Out[16]:
col1 col2
0 1 First
1 2 Second
2 3 Third
3 6 Sixth
4 4 Fourth
5 5 Fifth
6 7 Seventh
如您所见,test2
中的第二行现在位于底部。调用 pd.merge(test2, test1, how='outer', sort=False)
会得到类似的结果,但 test1
的第四行位于底部。坚持两个 DataFrame 中的条目顺序对我来说至关重要,所以这不是我想要的。
我还尝试过 update()
、combine_first()
和 replace()
,但它们提供了内部联接或左联接.
我怎样才能让pandas
做我想做的事?
最佳答案
您可以使用concat
接下来是 drop_duplicates
和 sort_index
:
df = pd.concat([test2, test1]).drop_duplicates().sort_index()
结果输出:
col1 col2
0 1 First
1 7 Seventh
2 2 Second
3 3 Third
3 6 Sixth
4 4 Fourth
5 5 Fifth
如果您希望新 DataFrame 的索引是唯一的,请执行 reset_index
最后:
df = pd.concat([test2, test1]).drop_duplicates().sort_index().reset_index(drop=True)
这给出了唯一索引:
col1 col2
0 1 First
1 7 Seventh
2 2 Second
3 3 Third
3 6 Sixth
4 4 Fourth
5 5 Fifth
关于python - Pandas 外部合并同一 DataFrame 的两个版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40683391/