I have a df column that has values ranging from -5 to 10. I want to change values <= -1 to negative
, all 0 values to neutral
, and all values >=
As roganjosh pointed out, you're doing your replacement in 3 steps - this is causing a problem because after step 1, you end up with a column of mixed dtypes, so subsequent equality checks start to fail.
You can either assign to a new column, or use numpy.select.
condlist = [
test['sentiment_score'] > 0,
test['sentiment_score'] < 0
]
choicelist = ['pos', 'neg']
test['sentiment_score'] = np.select(
condlist, choicelist, default='neutral')
Another alternative is to define a custom function:
def transform_sentiment(x):
if x < 0:
return 'Negative'
elif x == 0:
return 'Neutral'
else:
return 'Positive'
df['Sentiment_new'] = df['Sentiment'].apply(lambda x: transform_sentiment(x))