Home > Software engineering >  Renaming Pandas Column Names to String Datatype
Renaming Pandas Column Names to String Datatype

Time:08-12

I have a df with column names that do not appear to be of the typcial string datatype. I am trying to rename these column names to give them the same name. I have tried this and I end up with an error. Here is my df with column names:

dfap.columns
Out[169]: Index(['month', 'plant_name', 0, 1, 2, 3, 4], dtype='object')

Here is my attempt at renaming columns 2,3,4,5,6 or 2:7

dfap.columns[2:7] = [ 'Adj_Prod']
Traceback (most recent call last):

  File "<ipython-input-175-ebec554a2fd1>", line 1, in <module>
    dfap.columns[2:7] = [ 'Adj_Prod']

  File "C:\Users\U321103\Anaconda3\envs\Maps2\lib\site-packages\pandas\core\indexes\base.py", line 4585, in __setitem__
    raise TypeError("Index does not support mutable operations")

TypeError: Index does not support mutable operations

Thank you,

CodePudding user response:

You can't rename only some columns using that method.

You can do

tempcols=dfap.columns
tempcols[2:7]=newcols 
dfap.columns=tempcols

Of course you'll want newcols to be the same len as what you're replacing. In your example you're only assigning a len 1 list.

You could do.

dfap.rename(columns=dict_of_name_changes, inplace=True)

The dict needs for the key to be the existing name and the value to be the new name. In this method you can rename as few columns as you want.

CodePudding user response:

You could use rename(columns= with a lambda function to handle the renaming logic.

df.rename(columns=lambda x: x if type(x)!=int else 'Adj_Prod') 

Result

Columns: [month, plant_name, Adj_Prod, Adj_Prod, Adj_Prod, Adj_Prod, Adj_Prod]
  • Related