Pandas:向多索引列数据框添加一列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16088741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: add a column to a multiindex column dataframe
提问by spencerlyon2
I would like to add a column to the second level of a multiindex column dataframe.
我想将一列添加到多索引列数据框的第二级。
In [151]: df
Out[151]:
first bar baz
second one two one two
A 0.487880 -0.487661 -1.030176 0.100813
B 0.267913 1.918923 0.132791 0.178503
C 1.550526 -0.312235 -1.177689 -0.081596
The usual trick of direct assignment does not work:
通常的直接赋值技巧不起作用:
In [152]: df['bar']['three'] = [0, 1, 2]
In [153]: df
Out[153]:
first bar baz
second one two one two
A 0.487880 -0.487661 -1.030176 0.100813
B 0.267913 1.918923 0.132791 0.178503
C 1.550526 -0.312235 -1.177689 -0.081596
How can I add the third row to under "bar"?
如何将第三行添加到“栏”下?
回答by spencerlyon2
It's actually pretty simple (FWIW, I originally thought to do it your way):
它实际上非常简单(FWIW,我原本想按照你的方式来做):
df['bar', 'three'] = [0, 1, 2]
df = df.sort_index(axis=1)
print(df)
bar baz
one two three one two
A -0.212901 0.503615 0 -1.660945 0.446778
B -0.803926 -0.417570 1 -0.336827 0.989343
C 3.400885 -0.214245 2 0.895745 1.011671
回答by MaxU
If we want to add a multi-level column:
如果我们想添加一个多级列:
Source DF:
来源DF:
In [221]: df
Out[221]:
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
Option 1: adding result of division: bar / baz
as a new foo
column
选项 1:添加除法结果:bar / baz
作为新foo
列
In [222]: df = df.join(df[['bar']].div(df['baz']).rename(columns={'bar':'foo'}))
In [223]: df
Out[223]:
first bar baz foo
second one two one two one two
A -1.089798 2.053026 0.470218 1.440740 -2.317647 1.424980
B 0.488875 0.428836 1.413451 -0.683677 0.345873 -0.627250
C -0.243064 -0.069446 -0.911166 0.478370 0.266761 -0.145172
Option 2: adding multi-level column with three "sub-columns":
选项 2:添加具有三个“子列”的多级列:
In [235]: df = df.join(pd.DataFrame(np.random.rand(3,3),
...: columns=pd.MultiIndex.from_product([['new'], ['one','two','three']]),
...: index=df.index))
In [236]: df
Out[236]:
first bar baz new
second one two one two one two three
A -1.089798 2.053026 0.470218 1.440740 0.274291 0.636257 0.091048
B 0.488875 0.428836 1.413451 -0.683677 0.668157 0.456931 0.227568
C -0.243064 -0.069446 -0.911166 0.478370 0.333824 0.363060 0.949672