用 pandas 合并索引上的数据框 [英] Merging dataframes on index with pandas

查看:79
本文介绍了用 pandas 合并索引上的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据框,每个数据框都有两个索引列.我想将它们合并.例如,第一个数据帧如下:

I have two dataframes and each one has two index columns. I would like to merge them. For example, the first dataframe is the following:

                   V1

A      1/1/2012    12
       2/1/2012    14
B      1/1/2012    15
       2/1/2012    8
C      1/1/2012    17
       2/1/2012    9

第二个数据帧如下:

                   V2

A      1/1/2012    15
       3/1/2012    21             
B      1/1/2012    24
       2/1/2012    9
D      1/1/2012    7
       2/1/2012    16

因此,我想得到以下信息:

and as result I would like to get the following:

                   V1   V2

A      1/1/2012    12   15
       2/1/2012    14   N/A
       3/1/2012    N/A  21           
B      1/1/2012    15   24
       2/1/2012    8    9
C      1/1/2012    7    N/A
       2/1/2012    16   N/A
D      1/1/2012    N/A  7
       2/1/2012    N/A  16

我已经尝试过使用pd.merge.join方法的一些版本,但是似乎没有任何效果.你有什么建议吗?

I have tried a few versions using the pd.merge and .join methods, but nothing seems to work. Do you have any suggestions?

推荐答案

您应该能够使用join,默认情况下,它会连接到索引.给定您想要的结果,您必须使用outer作为联接类型.

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

签名:_.join(其他,on =无,how ='左',lsuffix ='',rsuffix ='',sort = False) Docstring: 在索引或键上将列与其他DataFrame连接起来 柱子.通过索引一次有效地连接多个DataFrame对象 传递列表.

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

这篇关于用 pandas 合并索引上的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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