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

Avoid NaN values in .Applymap()

I am trying apply a str.title but it changes Nan values which are actually blank to the text ‘Nan’ this is causing issues farther in the code.

df_cols = ['First Name','Last Name', 'State/Province','Country','Industry','System Type','Account Type', 'Customer Segment']
df[df_cols] = df[df_cols].astype(str).apply(lambda col: col.str.title())

this is what i have tried

df[df_cols] = df[df_cols].astype(str).apply(lambda col: col.str.title()if pd.notnull(x) else '')

But this is getting a truth value error message. Is there a better way to ignore Nan?

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 :

One easy way is to mask the output:

df[df_cols] = (df[df_cols].astype(str)
                 .apply(lambda col: col.str.title())
                 .where(df[df_cols].notna())
              )
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