格式化分组数据帧

时间:2017-11-01 14:56:43

标签: pandas dataframe group-by pandas-groupby

我正在阅读以下有关分组的教程,https://chrisalbon.com/python/pandas_apply_operations_to_groups.html

在下面概述的小组之后,我如何转换为只有团,第1,第2 作为其列的数据框?

Grouped Dataframe

2 个答案:

答案 0 :(得分:2)

我认为您尝试从数据框中删除该公司,因此请使用

df.columns.name = ''

如果您想重置索引,请使用

df = df.reset_index()

输出:

ndf = df['preTestScore'].groupby([df['regiment'], df['company']]).mean().unstack()
ndf.columns.name = ''
            1st   2nd
regiment              
Dragoons     3.5  27.5
Nighthawks  14.0  16.5
Scouts       2.5   2.5

<强> To have dataframe simply has regiment, 1st, 2nd as its columns

ndf = ndf.reset_index() 
     regiment   1st   2nd
0    Dragoons   3.5  27.5
1  Nighthawks  14.0  16.5
2      Scouts   2.5   2.5

答案 1 :(得分:0)

使用rename_axis

df.rename_axis(None,1)