Search code examples
pythonpandaslambdafor-in-loop

Multiply if on lambda in python


I would like create lambda which be will give me 3 results if greater than 0.3 is positive if between 0.3 to -0.3 neutral less than 0.3 below

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')

Nothing is work, im beginner with that ! May please for help


Solution

  • It might be easier if you use a regular function instead of a 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)
    

    Edit: For a 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")