python 小于等于号不支持int string_Python-'str'和'int'的实例之间不支持'TypeError:'< ='...

在尝试将数据框df中'sentiment_score'列的值根据条件转换为'negative'、'neutral'和'positive'标签时,遇到了TypeError。问题出在将负数转换为标签后,列中混合了字符串和整数类型。解决方案是使用numpy的select函数,避免在操作中导致数据类型的不匹配。
摘要由CSDN通过智能技术生成

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. 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

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. 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.

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')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值