[英]Python Pandas Dataframe - Create new column using a conditional/applying a function based on another column
I'm new to Python so I'm still getting to grips with it.我是 Python 的新手,所以我仍在掌握它。
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().本质上,在我的 Pandas Datframe 中,我有一个“评论”列,并希望创建一个名为“可读性”的新列 - 对于非空行/值,我将“评论”值传递给 textstat.flesch_reading_ease()。 But if 'Comments' are null/NaN - the value in 'Readability' would simply be 0.0.但是,如果“评论”为空/NaN - “可读性”中的值将只是 0.0。 . . The NaN values are part of my analysis - so I don't want to omit them in this case. NaN 值是我分析的一部分——所以我不想在这种情况下省略它们。
#Pseudo If null x -> 0.0, else textstat.flesch_reading_ease(x) #Pseudo If null x -> 0.0,否则 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?在代码方面,我一直在熟悉 pd.loc() - 但我认为在这种情况下它不可行?
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'这将返回 'float' object 没有属性 '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:)如果更容易理解,也很高兴看到 2/3 步的答案:)
Thanks!谢谢!
Example of 'Comments' column //i.stack.imgur.com/cZAWQ.png “评论”列示例 //i.stack.imgur.com/cZAWQ.png
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.