python - Pandas:将多列添加到多索引列数据框中
问题描述
这个问题试图概括为这个问题提供的解决方案:
我需要为每个列索引生成一列。
spencerlyon2
当我们要添加单列时,提供的解决方案有效:
df['bar', 'three'] = [0, 1, 2]
但是,我想为每个第一级列索引概括此操作。
来源 DF:
In [1]: df
Out[2]:
first bar baz
second one two one two
A -1.089798 2.053026 0.470218 1.440740
B 0.488875 0.428836 1.413451 -0.683677
C -0.243064 -0.069446 -0.911166 0.478370
下面的目标 DF,要求该列是其各自索引的和列three
的相加。one
two
In [1]: df
Out[2]:
first bar baz
second one two three one two three
A -1.089798 2.053026 0.963228 1.440740 -2.317647 -0.876907
B 0.488875 0.428836 0.917711 -0.683677 0.345873 -0.337804
C -0.243064 -0.069446 -0.312510 0.478370 0.266761 0.745131
解决方案
您可以使用join
两个具有相同索引的数据框来一次创建一堆列。
groupby
首先,使用反对计算总和axis=1
ndf = df.groupby(df.columns.get_level_values(0), axis=1).sum()
bar baz
A 0.963228 1.910958
B 0.917711 0.729774
C -0.312510 -0.432796
(PS:如果你有两个以上的列,你可以这样做
df.loc[:, (slice(None), ['one', 'two'])].groupby(df.columns.get_level_values(0), axis=1).sum()
先只切片“一”和“二”列,然后再 groupby
切片)
然后,使其与您的列索引匹配,即使其成为 MultiIndexed 数据框,就像您的原始数据框一样
ndf.columns = pd.MultiIndex.from_product([ndf.columns, ['three']])
bar baz
three three
A 0.963228 1.910958
B 0.917711 0.729774
C -0.312510 -0.432796
最后,df.join
finaldf = df.join(ndf).sort_index(axis=1)
如果您真的关心订购,请使用reindex
finaldf.reindex(['one', 'two', 'three'], axis=1, level=1)
first bar baz
second one two three one two three
A -1.089798 2.053026 0.963228 0.470218 1.440740 1.910958
B 0.488875 0.428836 0.917711 1.413451 -0.683677 0.729774
C -0.243064 -0.069446 -0.312510 -0.911166 0.478370 -0.432796
推荐阅读
- flutter - Flutter 中 ListView 项的动态高度
- elasticsearch - 在索引上检测到特定数量的分片时发出警报
- javascript - 如何使用 framer x 创建功能推送通知(在 x 时间后触发)组件?
- python - Django在rest-auth注册后不发送电子邮件
- html - 我遇到了文本区域、按钮及其布局的问题
- c# - WebBrowser 打印后关闭应用程序
- css - gojs图在IE11中不显示
- permissions - queryPermissionsByGroup 在 android Q 上返回 null
- sql-server - 根据某列对已经汇总的列进行汇总
- c - 不能指向从 C 中的文件中读取的结构