0

I have the following dataframe:

enter image description here

I want to rename the columns to snake case using a function I defined:

def to_snakecase(cols):
map_dict = {}
for col in cols:
    map_dict[col] = col.lower().strip().replace(' ', '_')

When I write the code:

covid_df.rename(to_snakecase(covid_df.columns), axis=1, inplace=True)

I get the error: must pass an index to rename

I have looked at the documentation but haven't figured it out. Please help. Thank you.

Alejandro L
  • 147
  • 1
  • 9

1 Answers1

2

First of all your function returns None and rename function cannot find Indexer

def to_snakecase(cols):
    map_dict = {}
    for col in cols:
        map_dict[col] = col.lower().strip().replace(' ', '_')
    return map_dict

I belive that the most expresive way to rename columns is to use keyword columns in rename function. Your code could look as follows

covid_df.rename(columns=to_snakecase(covid_df.columns), inplace=True)
  • Thank you Marek. The problem was that the function returned None, therefore there was no index in the first place. Thank you – Alejandro L Nov 28 '20 at 22:40