pandas 在列级连接数据帧时添加键 [英] Pandas add keys while concatenating dataframes at column level

查看:61
本文介绍了 pandas 在列级连接数据帧时添加键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Pandas 0.19.2文档,我可以提供 keys 参数来创建结果的多索引DataFrame.一个示例(来自pandas文档)是:

As per Pandas 0.19.2 documentation, I can provide keys argument to create a resulting multi-index DataFrame. An example (from pandas documents ) is :

result = pd.concat(frames, keys=['x', 'y', 'z'])

如何连接数据框,以便可以在列级而不是索引级提供键?

How would I concat the dataframe so that I can provide the keys at the column level instead of index level ?

我基本上需要的是这样的东西:

What I basically need is something like this :

其中df1和df2是连续的.

where df1 and df2 are to be concat.

推荐答案

keys参数支持.concat.html"rel =" nofollow noreferrer> pd.concat ,当指定axis=1时:

This is supported by keys parameter of pd.concat when specifying axis=1:

df1 = pd.DataFrame(np.random.random((4, 4)), columns=list('ABCD'))
df2 = pd.DataFrame(np.random.random((4, 3)), columns=list('BDF'), index=[2, 3, 6, 7])

df = pd.concat([df1, df2], keys=['X', 'Y'], axis=1)

结果输出:

          X                                       Y                    
          A         B         C         D         B         D         F
0  0.654406  0.495906  0.601100  0.309276       NaN       NaN       NaN
1  0.020527  0.814065  0.907590  0.924307       NaN       NaN       NaN
2  0.239598  0.089270  0.033585  0.870829  0.882028  0.626650  0.622856
3  0.983942  0.103573  0.370121  0.070442  0.986487  0.848203  0.089874
6       NaN       NaN       NaN       NaN  0.664507  0.319789  0.868133
7       NaN       NaN       NaN       NaN  0.341145  0.308469  0.884074

这篇关于 pandas 在列级连接数据帧时添加键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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