我有一个df列,它的值从-5到10。我想将值<;=-1更改为negative,将所有0值更改为neutral,将所有值>;=1更改为positive。但是,下面的代码为“negative”生成以下错误。# Function to change values to labels
test.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 positiveFile "pandas_libs\ops.pyx", line 98, in pandas._libs.ops.scalar_compare
TypeError: '<=' not supported between instances of 'str' and 'int
我假设这与函数将负数视为字符串而不是float/int有关,但是我尝试了以下代码来更正此错误,但它什么也没有更改。任何帮助都将不胜感激。test['sentiment_score'] = test['sentiment_score'].astype(float)
test['sentiment_score'] = test['sentiment_score'].apply(pd.as_numeric)