Home > database >  Avoid NaN values in .Applymap()
Avoid NaN values in .Applymap()

Time:08-31

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?

CodePudding user response:

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())
              )
  • Related