How can I change the IF statement? I only get invalid syntax
predicted_sentiment = [if score < 0 then 'Negative', if score == 0 then 'Neutral' if score > 0 then 'Positive' for score in sentiment_polarity]
CodePudding user response:
You probably want:
predicted_sentiment = [
('Negative' if score < 0 else 'Neutral' if score == 0 else 'Positive')
for score in sentiment_polarity
]
CodePudding user response:
You can use a lambda that would increase readability (a bit subjective) and simplifies the way you can test it (more objective)
>>> c = lambda x: 'Negative' if x < 0 else 'Neutral' if x == 0 else 'Positive'
>>> c(2)
'Positive'
>>> c(-2)
'Negative'
>>> c(0)
'Neutral'
>>> sentiment_polarity = [1, 0, -2, 3, -4]
>>> predicted_sentiment = [c(s) for s in sentiment_polarity]
>>> predicted_sentiment
['Positive', 'Neutral', 'Negative', 'Positive', 'Negative']
edit
You can also use numpy.sign()
like this
c = lambda x: ['Negative', 'Neutral', 'Positive'][numpy.sign(x) 1]