[英]Python - 'TypeError: '<=' not supported between instances of 'str' and 'int''
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 >= 1 to positive
. 我有一个df列,其值的范围是-5到10。我想将<= -1的值更改为
negative
,将所有0的值更改为neutral
,将所有> = 1的值更改为positive
。 The code below, however, produces the following error for '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 positive
File "pandas_libs\\ops.pyx", line 98, in pandas._libs.ops.scalar_compare TypeError: '<=' not supported between instances of 'str' and 'int
pandas._libs.ops.scalar_compare TypeError中的文件“ pandas_libs \\ ops.pyx”,行98,TypeError:'str'和'int实例之间不支持'<='
I assume that this has something to do with the function seeing negative numbers as string rather than float/int, however I've tried the following code to correct this error and it changes nothing. 我认为这与将负数视为字符串而不是float / int的函数有关,但是我尝试了以下代码来更正此错误,并且它什么都不会改变。 Any help would be appreciated.
任何帮助,将不胜感激。
test['sentiment_score'] = test['sentiment_score'].astype(float)
test['sentiment_score'] = test['sentiment_score'].apply(pd.as_numeric)
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. 正如roganjosh所指出的,您要分3步进行替换-这会引起问题,因为在第1步之后,您将得到一列混合dtypes,因此后续的相等性检查开始失败。
You can either assign to a new column, or use numpy.select
. 您可以分配给新列,也可以使用
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.