Home > Blockchain >  Python Pandas Dataframe - Create new column using a conditional/applying a function based on another
Python Pandas Dataframe - Create new column using a conditional/applying a function based on another

Time:08-21

I'm new to Python so I'm still getting to grips with it.

Essentially, in my Pandas Datframe I have a column 'Comments' and would like to create a new column called 'Readability' - where for non-null rows/values, I pass the 'Comments' value into textstat.flesch_reading_ease(). But if 'Comments' are null/NaN - the value in 'Readability' would simply be 0.0. . The NaN values are part of my analysis - so I don't want to omit them in this case.

#Pseudo If null x -> 0.0 , else textstat.flesch_reading_ease(x)

See Image.

In terms of code, I have been building familiarity with pd.loc() - but I don't think it's viable in this case?

Alternatively, I have tried

repairs['Readibility'] = repairs['Comment'].apply(lambda x: 0.0 if x.isnull() else textstat.flesch_reading_ease(x))

This returns 'float' object has no attribute 'isnull'

Any ideas how to tweak my approach? I would also appreciate the why/how behind solutions. Also happy to see 2/3 step answers if it's easier to understand :)

Thanks!

Example of 'Comments' column//i.stack.imgur.com/cZAWQ.png

CodePudding user response:

Use:

repairs['Readibility'] = repairs['Comment'].apply(lambda x: 0.0 if pd.isna(x) else textstat.flesch_reading_ease(x))

Another idea:

repairs['Readibility'] = 0
repairs['Readibility'] = repairs.loc['Comment'].notna(), "Comment"].apply(textstat.flesch_reading_ease)
  • Related