简体   繁体   中英

Apply (in Pandas) to Multiple Columns

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.

RENAME MULTIPLE COLUMNS Using df.rename:

Use the df.rename() function and refer the columns to be renamed:

renamed_df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})

Or rename the existing DF instead of creating a new DF

df.rename(columns={'oldName1': 'newName1', 'oldName2})

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))

Have you tried to used pandas.DataFrame.applymap?

It will apply you function to all the DataFrame and I understand that is what you want.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM