Avoid NaN values in .Applymap()

Question:

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?

Asked By: flipping flop

||

Answers:

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())
              )
Answered By: Quang Hoang
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.