Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

renaming columns after group by and sum in pandas dataframe

Tags:

pandas

This is my group by command:

pdf_chart_data1 = pdf_chart_data.groupby('sell').value.agg(['sum']).rename(
    columns={'sum':'valuesum','sell' : 'selltime'}
)

I am able to change the column name for value but not for 'sell'. Please help to resolve this issue.

like image 998
LKA Avatar asked Jun 07 '17 15:06

LKA


People also ask

How do I change the column name after Groupby in Pandas?

The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename method. See this deprecation note in the documentation for more detail.

How do you name a Groupby column?

You call . groupby() and pass the name of the column that you want to group on, which is "state" . Then, you use ["last_name"] to specify the columns on which you want to perform the actual aggregation.


2 Answers

You cannot rename it, because it is index. You can add as_index=False for return DataFrame or add reset_index:

pdf_chart_data1=pdf_chart_data.groupby('sell', as_index=False)['value'].sum()
                              .rename(columns={'sum':'valuesum','sell' : 'selltime'})

Or:

pdf_chart_data1=pdf_chart_data.groupby('sell')['value'].sum()
                          .reset_index()
                          .rename(columns={'sum':'valuesum','sell' : 'selltime'})
like image 191
jezrael Avatar answered Oct 11 '22 06:10

jezrael


df = df.groupby('col1')['col1'].count()
df1= df.to_frame().rename(columns={'col1':'new_name'}).reset_index()
like image 2
Joselin Ceron Avatar answered Oct 11 '22 05:10

Joselin Ceron