Nicholas
Nicholas

Reputation: 3737

Python Pandas - Groupby and Mean, but keep column name

I am trying to find the mean of a column for each unique value in another column, and am using the code:

A_df = B.groupby('R')['L'].mean

And I get the mean value for each value in 'R', but the mean values has no column name, so I cant sort on it.

Is there a way of doing what the above does, but give the mean values a column name so I can sort on it?

Thank you

Upvotes: 2

Views: 2357

Answers (1)

jezrael
jezrael

Reputation: 862751

Use parameter as_index=False or reset_index:

A_df = B.groupby('R', as_index=False)['L'].mean()

Or:

A_df = B.groupby('R')['L'].mean().reset_index()

Upvotes: 3

Related Questions