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

前端 未结 2 803
暖寄归人
暖寄归人 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')
    
    0 讨论(0)
  • 2021-01-06 13:02

    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))
    
    0 讨论(0)
提交回复
热议问题