在新索引级别下合并 pandas 数据框 [英] merge pandas dataframes under new index level

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

问题描述

我有2个 pandas DataFrame act exp 我想合并为一个数据帧 df :

I have 2 pandas DataFrames act and exp that I want to combine into a single dataframe df:

import pandas as pd
from numpy.random import rand
act = pd.DataFrame(rand(3,2), columns=['a', 'b'])
exp = pd.DataFrame(rand(3,2), columns=['a', 'c'])

act #have

          a         b
0  0.853910  0.405463
1  0.822641  0.255832
2  0.673718  0.313768

exp #have

          a         c
0  0.464781  0.325553
1  0.565531  0.269678
2  0.363693  0.775927

数据框 df 应包含比 act exp 多一列的列索引级别,并在其自己的0级标识符下包含每个索引级别,例如所以:

Dataframe df should contain one more column index level than act and exp, and contain each under its own level-0 identifier, like so:

df  #want

        act                 exp          
          a         b         a         c
0  0.853910  0.405463  0.464781  0.325553
1  0.822641  0.255832  0.565531  0.269678
2  0.673718  0.313768  0.363693  0.775927

关于如何执行此操作的任何想法?

Any ideas as to how to do this?

有点像 merge 合并两个框架:

act.merge(exp, left_index=True, right_index=True, suffixes=['_act', '_exp'])

      a_act         b     a_exp         c
0  0.853910  0.405463  0.464781  0.325553
1  0.822641  0.255832  0.565531  0.269678
2  0.673718  0.313768  0.363693  0.775927

...但是使用附加级别(而不是后缀)来防止名称冲突.

...but using an additional level, instead of a suffix, to prevent name collisions.

我尝试过:

#not working
pd.DataFrame({'act': act, 'exp':exp})  

我可以使用循环逐个序列地构建 df ,但这似乎不正确.

I could use loops to build up the df series-by-series, but that doesn't seem right.

非常感谢.

推荐答案

也许您可以尝试使用 concat :

pd.concat([act, exp], axis=1, keys=['act', 'exp'])

结果:

          act                      exp
       a           b             a           c
0   0.604027    0.933399    0.830059    0.317602
1   0.992192    0.991513    0.397223    0.904166
2   0.382579    0.981182    0.862077    0.239373

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

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