将索引上的数据帧与 pandas 合并 [英] Merging dataframes on index with pandas

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

问题描述

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

 V1A 1/1/2012 122/1/2012 14乙 1/1/2012 152/1/2012 8C 1/1/2012 172/1/2012 9

第二个数据框如下:

 V2A 1/1/2012 152012/3/1 21乙 2012 年 1 月 1 日 242/1/2012 9D 1/1/2012 72/1/2012 16

结果我想得到以下内容:

 V1 V2A 1/1/2012 12 152/1/2012 14 不适用3/1/2012 不适用 21乙 2012 年 1 月 1 日 15 242/1/2012 8 9C 1/1/2012 7 不适用2/1/2012 16 不适用D 1/1/2012 不适用 72/1/2012 不适用 16

我使用 pd.merge.join 方法尝试了几个版本,但似乎没有任何效果.你有什么建议吗?

解决方案

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

<预><代码>>>>df1.join(df2, how='outer')V1 V2A 1/1/2012 12 152/1/2012 14 NaN2012 年 3 月 1 日 NaN 21乙 2012 年 1 月 1 日 15 242/1/2012 8 9C 1/1/2012 17 NaN2/1/2012 9 NaND 1/1/2012 NaN 72/1/2012 NaN 16

<块引用>

签名:_.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False)文档字符串:在索引或键上将列与其他 DataFrame 连接柱子.一次通过索引有效地连接多个 DataFrame 对象传递一个列表.

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

The second dataframe is the following:

                   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

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

解决方案

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

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天全站免登陆