0

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

3
  • 1
    Who on earth force you to use .apply(lambda ... in thise case. Just np.where and .between... Commented Apr 13, 2021 at 14:44
  • 2
    Agree with Quang m, here is an example you can look at : stackoverflow.com/questions/19913659/… Commented Apr 13, 2021 at 14:49
  • Hey Quang, i got this form my study . I agree with you, better for me will be always use small def with if statment. But could you let me know when w should use lambda ? Commented Apr 13, 2021 at 15:26

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

2 Comments

thanks i know, but i have excersie to use lambda unfortunetly :(
I'm strongly against apply in this case, but if you insist on apply and lambda: .apply(lambda x: polarity(x))
0

Try using if-elif-else in funtion.

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)

Or in one line with lambda function

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.