Alejandro L
Alejandro L

Reputation: 149

Must pass an index to rename - python

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.

Upvotes: 0

Views: 1286

Answers (1)

Marek Złakowski
Marek Złakowski

Reputation: 331

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)

Upvotes: 2

Related Questions