【发布时间】:2020-03-12 11:24:01
【问题描述】:
这个问题是试图概括为这个问题提供的解决方案:
Pandas: add a column to a multiindex column dataframe
我需要为每个列索引生成一列。
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
【问题讨论】: