如果在 python 中的 lambda 上乘以

Multiply if on lambda in python

我想创建 lambda,它会给我 3 个结果,如果大于 0.3 是正的,如果在 0.3 到 -0.3 之间,中性低于 0.3

df['sentiment_rat2'] = df['sentiment'].apply(lambda sentiment: 'positiv' if sentiment.polarity >= 0.3 else 'neutral' <= 0.3 sentiment.polarity =< -0.3  else 'negative')
df['sentiment_rat2'] = df['sentiment'].apply(lambda sentiment: 'positiv' if sentiment.polarity >= 0.3 if 'neutral' <= 0.3 sentiment.polarity =< -0.3  else 'negative')

没有什么是行得通的,我是初学者!可以请帮助

如果使用常规函数而不是 lambda 可能会更容易。

def polarity_sorter(value):
    if value.polarity > 0.3:
        return "Postivie"
    elif -0.3 <= value.polarity <= 0.3:
        return "Neutral"
    else: #Anything below 0.3
        return "Negative"

df['sentiment_rat2'] = df['sentiment'].apply(polarity_sorter)

编辑:对于 lambda: Putting an if-elif-else statement on one line?

df['sentiment_rat2'] = df['sentiment'].apply(lambda value: "Positive" if value > .3 else "Negative" if value <-.3 else "Neutral")

尝试在函数中使用 if-elif-else

def rate(sentiment):
    if sentiment >= 0.3:
        return 'positive'
    elif sentiment >= -0.3:
        return 'neutral'
    else:
        return 'negative'

df['sentiment_rat2'] = df['sentiment'].apply(rate)

或与 lambda 函数在一行中

df['sentiment_rat2'] = df['sentiment'].apply(lambda sentiment: 'positive' if sentiment >= 0.3 else ('neutral' if sentiment >= -0.3 else 'negative'))