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

  • 1
    Who on earth force you to use `.apply(lambda ...` in thise case. Just `np.where` and `.between`... – Quang Hoang Apr 13 '21 at 14:44
  • 2
    Agree with Quang m, here is an example you can look at : https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column – anky Apr 13 '21 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 ? –  Apr 13 '21 at 15:26

2 Answers2

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")
lwashington27
  • 320
  • 2
  • 14
  • thanks i know, but i have excersie to use lambda unfortunetly :( –  Apr 13 '21 at 14:43
  • I'm strongly against `apply` in this case, but if you insist on `apply` and `lambda`: `.apply(lambda x: polarity(x))` – Quang Hoang Apr 13 '21 at 14:45
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'))
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52