1

I tried to do this:

districtident.rename(columns={'leaid':'nces'},inplace=True)

and it failed: enter image description here

Other things that didn't work:

districtident = districtident.rename(columns={'leaid':'nces'})

Renaming the column names of pandas dataframe is not working as expected - python

renaming columns in pandas doesn't do anything

Wasn't great either.

Here's an obvious appeal:

obvious appeal

Alas, no.

Restarting the kernel didnt' work either. The only thing that worked was:

districtident['nces'] = districtident['leaid']
disrictident.drop(['leaid'],axis=1,inplace=True)

But that's really not the best, I feel. Especially if I need to do a number of columns.

  • 2
    please post a sample of the `districtident` df. Copy paste it in the question and format as code. Avoid posting images of the data – Vivek Kalyanarangan Aug 17 '21 at 15:37
  • 1
    I tried your data frame with fake data and the same names of columns and I renamed it. It works! I suggest posting a data frame itself in your question to see if there is any hidden problem. –  Aug 17 '21 at 16:18
  • Do you get anything with `errors="raise"` in your rename call? – s_pike Aug 17 '21 at 17:21
  • And have you got duplicate column names at all? https://stackoverflow.com/questions/40774787/renaming-columns-in-a-pandas-dataframe-with-duplicate-column-names – s_pike Aug 17 '21 at 17:26

1 Answers1

0

Ran into the same problem with one specific DF after I concatenated a Pandas DF with two Pandas Series. Tried to use several variants of df.rename() listed below. None of them worked.

# using column name and axis 
df = df.rename({'oldName1':'newName1', 'oldName2':'newName2'}, axis = 'columns')

# using column index and axis
df = df.rename({28:'newName1', 29:'newName2'}, axis = 'columns')

# using column name
df = df.rename(columns = {'oldName1':'newName1', 'oldName2':'newName2'})

# using column name and inplace function
df.rename(columns = {'oldName1':'newName1', 'oldName2':'newName2'}, inplace = True)

# using column index and inplace function
df.rename(columns = {28:'newName1', 29:'newName2'}, inplace = True)

Also tried this suggestion df.rename(columns={(28, 'newName1'): 'newName1'}, inplace = True, which did not work.

What worked is this: df.columns.values[27]= 'newName1'
This is of course not ideal as it needs to be done individually for each column. As I only had 2 columns to rename this is ok for me. If possible I recommend to use df.rename(), but if it just doesn't work this may be an alternative.

Simone
  • 497
  • 5
  • 19