I have a list of dataframes I have saved in a variable x.
x=[df_1963,df_1974,df_1985,df_1996,df_2007,df_2018]
I wish to change all the headers to lowercase but nothing happens after the running the code below.
for df in x:
for column in df.columns:
df = df.withColumnRenamed(column, '_'.join(column.split()).lower())
CodePudding user response:
You can do it in a list and dict comprehension way. Try with:
renamed_x = [a.rename(columns={y:y.lower() for y in a}) for a in x]
The inner dict comprehension generates a dictionary with the columns' original values and its lowercase, so that is how each dataframe's columns will be renamed in lowercase; while the outer list comprehension iterates over all the dfs.
CodePudding user response:
Can use df.columns
to access each df
's columns instead of looping through:
for df in x:
df.columns = df.columns.str.lower()
CodePudding user response:
You could use Series.map
for columns as well:
for df in x:
df.columns = df.columns.map(str.lower)