我有一个df列,其值的范围是-5到10。我想将值<= -1更改为negative,将所有0值更改为neutral,将所有值> = 1更改为positive。但是,下面的代码为“负”产生以下错误。# Function to change values to labelstest.loc[test['sentiment_score'] > 0, 'sentiment_score'] = 'positive'test.loc[test['sentiment_score'] == 0, 'sentiment_score'] = 'neutral'test.loc[test['sentiment_score'] < 0, 'sentiment_score'] = 'negative'Data: Data After Code:Index Sentiment Index Sentiment 0 2 0 positive 1 0 1 neutral 2 -3 2 -3 3 4 3 positive 4 -1 4 -1 ... ... k 5 k positivepandas._libs.ops.scalar_compare TypeError中的文件“ pandas_libs \ ops.pyx”,行98,TypeError:'str'和'int实例之间不支持'<='我认为这与将负数视为字符串而不是float / int的函数有关,但是我尝试了以下代码来更正此错误,并且它什么都不会改变。任何帮助,将不胜感激。test['sentiment_score'] = test['sentiment_score'].astype(float)test['sentiment_score'] = test['sentiment_score'].apply(pd.as_numeric)
2 回答
慕丝7291255
TA贡献1859条经验 获得超6个赞
另一种选择是定义一个自定义函数:
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))
添加回答
举报
0/150
提交
取消