opamp
opamp

Reputation: 91

Formatting Grouped Dataframe

I'm reading the following tutorial on group by, https://chrisalbon.com/python/pandas_apply_operations_to_groups.html.

After the group by outlined below, how can I convert to a data frame that simply has regiment, 1st, 2nd as its columns?

Grouped Dataframe

Upvotes: 0

Views: 862

Answers (2)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

I think your trying to remove that company from dataframe so use

df.columns.name = ''

In case you want to reset the index then use

df = df.reset_index()

Output :

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

Upvotes: 2

BENY
BENY

Reputation: 323236

By using rename_axis

df.rename_axis(None,1)

Upvotes: 0

Related Questions