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

Pandas replace and fillna if column begins with part of a string

I was wondering whether there is a way to use the .replace() and .fillna() for columns headers that begin with part of a string.

For example:

data['Q5_A'].fillna(value='Not Applicable', inplace=True)

This will only apply .fillna() to column Q5_A.

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

Similarily:

data["Q5_S"] = data["Q5_S"].replace(",", "", regex=True)

This will only apply .replace() to column Q5_S.

What if I would like it to apply to any columns that have "Q5_" in the header?

Thanks!

>Solution :

You can do a for loop and perform all the processes you need as well.

for header in data.columns:
    if "Q5" in header:
        data[header].fillna(value='Not Applicable', inplace=True)
        data[header] = data[header].replace(",", "", regex=True)
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