这个问题是为了概括解决此问题提供的解决方案而提出的:Pandas: add a column to a multiindex column dataframe。我需要为每个列索引生成一列。当我们想要添加单个列时,spencerlyon2提供的解决方案有效:df ['bar','three'] = [0,1,2]。但是,我希望将此操作推广到每个一级列索引。源数据框如下:
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要求三
列是其相应索引的一
列和二
列的加和。
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
df.columns.get_level_values(0)
时,在Groupby中出现了ValueErrorValueError("Grouper and axis must be same length")
。我将其更改为level=0
,然后它就可以工作了。有什么想法是什么导致了这个值错误? - SO_tourist