Python - 'TypeError: '<=' not supported between instances of 'str' and 'int''

前端 未结 2 805
暖寄归人
暖寄归人 2021-01-06 12:43

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

2条回答
  •  不思量自难忘°
    2021-01-06 13:01

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

提交回复
热议问题