合并列上的Pandas数据框,并按同一列对结果进行排序 [英] Merge Pandas dataframes on column, and have result sorted by same column

查看:191
本文介绍了合并列上的Pandas数据框,并按同一列对结果进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下两个数据框:

Let's say I have these two dataframes:

>>> import pandas as pd

>>> df1 = pd.DataFrame({"key":[1,3,5], "columnA":[30,40,50]})
>>> df1
   key  columnA
0    1       30
1    3       40
2    5       50

>>> df2 = pd.DataFrame({"key":[2,4], "columnB":[60,70]})
>>> df2
   key  columnB
0    2       60
1    4       70

我基本上想要一个新的数据框,具有键, columnA和 columnB,其中相应的数据分别从上述两个数据框中交织。我是这样做的:

I basically want a new dataframe, with "key", "columnA", and "columnB", where the corresponding data is "interleaved" from the two above dataframes, correspondingly. I did this:

>>> pd.merge(df1, df2, on='key', how='outer').astype('Int64')
   key  columnA  columnB
0    1       30     <NA>
1    3       40     <NA>
2    5       50     <NA>
3    2     <NA>       60
4    4     <NA>       70

...接近-但我希望输出为:

... which comes close - but I want the output to be:

   key  columnA  columnB
0    1       30     <NA>
1    2     <NA>       60
2    3       40     <NA>
3    4     <NA>       70
4    5       50     <NA>

如何实现?

推荐答案

您可以使用 sort_values ,然后 reset_index 以获得预期的输出。

You can use sort_values and then reset_index to achieve the expected output.

In [778]: pd.merge(df1, df2, on='key', how='outer').astype('Int64').sort_values('key').reset_index().drop('index',1)
Out[778]: 
   key  columnA  columnB
0    1       30     <NA>
1    2     <NA>       60
2    3       40     <NA>
3    4     <NA>       70
4    5       50     <NA>

或者您可以在 ignore_index = True 中传递 sort_values 参数本身:

Or you can pass ignore_index=True in the sort_values parameter itself:

In [795]: pd.merge(df1, df2, on='key', how='outer').astype('Int64').sort_values('key', ignore_index=True)
Out[795]: 
   key  columnA  columnB
0    1       30     <NA>
1    2     <NA>       60
2    3       40     <NA>
3    4     <NA>       70
4    5       50     <NA>

这篇关于合并列上的Pandas数据框,并按同一列对结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆