Home > Back-end >  How do i change column name in a dataframe in python pandas
How do i change column name in a dataframe in python pandas

Time:03-16

im new to python, i used to code...

StoreGrouper= DonHenSaless.groupby('Store')
StoreGrouperT= StoreGrouper["SalesDollars"].agg(np.sum)
StoreGrouperT.rename(columns={SalesDollars:TotalSalesDollars})

to group stores and sum by the SalesDollars then rename SalesDollars to TotalSalesDollars. it outputted the following error...

NameError: name 'SalesDollars' is not defined

I also tried using quotes

StoreGrouper= DonHenSaless.groupby('Store')
StoreGrouperT= StoreGrouper["SalesDollars"].agg(np.sum)
StoreGrouperT= StoreGrouperT.rename(columns={'SalesDollars':'TotalSalesDollars'})

This output the error: rename() got an unexpected keyword argument 'columns'

Here is my df df

CodePudding user response:

In order to rename a column you need quotes so it would be:

StoreGrouperT.rename(columns={'SalesDollars':'TotalSalesDollars'})

Also I usually assign it a variable

StoreGrouperT = StoreGrouperT.rename(columns={'SalesDollars':'TotalSalesDollars'})

CodePudding user response:

Use the pandas rename option to change the column name. You can also use inplace as true if you want your change to get reflected to the dataframe rather than saving it again on the df variable

df.rename(columns={'old_name':'new_name'}, inplace=True)
  • Related