Category Cat2 average
Beauty / Wellness / Healthcare 1 54.50
2 53.25
3 48.00
4 57.57
5 51.33
6 18.50
7 16.00
我有一个数据帧,多级。我需要将第二级转换为一个简单的列。可能吗? unstacking
会创建第1列到第7列。
作为补充:是否可以重命名组名(在0级和1级)?
答案 0 :(得分:2)
df.reset_index(['Cat2'])
会将Cat2
索引转换为列。
例如,
In [38]: df
Out[38]:
average
Category Cat2
Beauty / Wellness / Healthcare 1 54.50
2 53.25
3 48.00
4 57.57
5 51.33
6 18.50
7 16.00
In [39]: df.reset_index(['Cat2'])
Out[39]:
Cat2 average
Category
Beauty / Wellness / Healthcare 1 54.50
Beauty / Wellness / Healthcare 2 53.25
Beauty / Wellness / Healthcare 3 48.00
Beauty / Wellness / Healthcare 4 57.57
Beauty / Wellness / Healthcare 5 51.33
Beauty / Wellness / Healthcare 6 18.50
Beauty / Wellness / Healthcare 7 16.00
要更改索引级别名称,请使用df.index.names = ['foo', 'bar']
:
In [48]: df.index.names = ['foo', 'bar']
In [49]: df
Out[49]:
average
foo bar
Beauty / Wellness / Healthcare 1 54.50
2 53.25
3 48.00
4 57.57
5 51.33
6 18.50
7 16.00