Must pass and index to rename

Hi,

I have the following dataframe:

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.

Hi @ale_aleivaar,

With your function everything is ok. For renaming the columns, use the following code:

new_columns = []
for c in covid_df.columns:
    column_snake = to_snakecase(c)
    new_columns.append(column_snake)

covid_df.columns = new_columns

The last line will re-assign in-place new column names to your columns.

1 Like

Thank you @Elena_Kosourova. This is a useful alternative. The solution is adding return map_dict to the to_snakecase function.

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

Ah, yes, it also works perfectly!

1 Like