Reputation: 591
I'm trying to run a code to rename fields in one or more columns using apply... in a similar way to this link example.
However, I am not trying to succeed. I noticed that it is possible to run the function to rename if I am using only one column.
import pandas as pd
df = pd.DataFrame({'Município': {0:'Águas De Sao Pedro', 1:"Santa Barbara d'Oeste", 2:'Moji-Mirim'},
'Dept. Água': {0:'Cia. De Abastecimento', 1:'Serv. De Água E Esgoto', 2:'Cia. De São Paulo'}})
def rename_fields(x):
return(tab.
replace(' De ', ' de ').
replace(' E ', ' e ').
replace(' Sao ', ' São ').
replace('Moji', 'Mogi').
replace('Cia.', 'Companhia').
replace('Serv.', 'Serviço')
)
df['Município'] = df['Município'].apply(lambda x: rename_fields(x))
When I use two columns, it's a problem.
df[['Município', 'Dept. Água']] = df[['Município', 'Dept. Água']].apply(lambda x: rename_fields(x))
I noticed that this is related to the use of two [], that way [['Col1', Col2]]. Even if you use only one column, but this way [['Col1']], it doesn't work.
col = 'Município' # will work
col = ['Município'] # will not work
col = ['Município', 'Dept. Água'] # What I need!!
df[col] = df[col].apply(lambda x: rename_fields(x))
For me it would be important to work as a list, with one or more items, because in my original code I have a list created from a previous function, where I define in which columns certain functions should be applied.
Upvotes: 1
Views: 237
Reputation: 23
If is importanto to you use the list of columns, you can use this:
for column in columns:
df[column] = df[column].apply(lambda x: rename_fields(x))
Upvotes: 0
Reputation: 11
Use the df.rename() function and refer the columns to be renamed:
renamed_df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
df.rename(columns={'oldName1': 'newName1', 'oldName2})
Upvotes: 1