这个问题试图概括为此问题提供的解决方案:
\n\n\n\n我需要为每个列索引生成一列。
\n\nspencerlyon2当我们想要添加单个列时,提供的解决方案有效:
df[\'bar\', \'three\'] = [0, 1, 2]
不过,我想将这个操作推广到每个第一级列索引。
\n\n来源DF:
\n\nIn [1]: df\nOut[2]:\nfirst bar baz\nsecond one two one two\nA -1.089798 2.053026 0.470218 1.440740\nB 0.488875 0.428836 1.413451 -0.683677\nC -0.243064 -0.069446 -0.911166 0.478370\nRun Code Online (Sandbox Code Playgroud)\n\n下面的目标 DF 要求该列是其各自索引的和列three的相加。onetwo
In [1]: df\nOut[2]:\nfirst bar baz \nsecond one two three one two three\nA -1.089798 2.053026 0.963228\xe2\x80\xac 1.440740 -2.317647 -0.876907\xe2\x80\xac\nB 0.488875 0.428836 0.917711 -0.683677 0.345873 -0.337804\xe2\x80\xac\nC -0.243064 -0.069446 -0.312510 0.478370 0.266761 0.745131\xe2\x80\xac\nRun Code Online (Sandbox Code Playgroud)\n
我从您的示例输入开始:
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
Run Code Online (Sandbox Code Playgroud)
要将新列添加到 MultiIndex 列的每个级别 0,您可以运行如下命令:
for c1 in df.columns.get_level_values('first').unique():
# New column int index
cInd = int(df.columns.get_loc(c1).stop)
col = (c1, 'three') # New column name
newVal = df[(c1, 'one')] + df[(c1, 'two')]
df.insert(loc=cInd, column=col, value=newVal) # Insert the new column
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,新列中的值是连续的数字,但在您的情况下根据您的意愿设置它们。
我的代码的结果(列排序后)是:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5909 次 |
| 最近记录: |