Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to apply multiple custom functions to the same column without using apply every time?

I have three functions:

def replace_date(x):
    pass

def replace_name(x):
    pass

def replace_occupation(x):
    pass 

They need to be applied to each row in a specific column. So far I write the code

df['mod'] = df['info'].apply(lambda row: replace_date(row)).apply(lambda row: replace_name(row)).apply(lambda row: replace_occupation(row)).apply(lambda row: re.sub(' +', ' ', row))

The last one I did not yet put into a separate function but I want to get rid of the three apply-s and write it in a nicer and more compact way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try

df['mod'] = df['info'].apply(lambda row: re.sub(' +', ' ', replace_occupation(replace_name(replace_date(row))))) 

It’s one apply() although slightly less readable due to the re.sub(' +', ' ', row) in the end.

More generally, it is

df['col'].apply(lambda row: h(f(g(row))))

for some functions f(), g(), and h().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading