Python-'str'和'int'的实例之间不支持'TypeError:'<='

Lau*_*ber 2 python pandas

我有一个df列,其值的范围是-5到10。我想将值<= -1更改为negative,将所有0值更改为neutral,将所有值> = 1更改为positive。但是,下面的代码为“负”产生以下错误。

# 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
Run Code Online (Sandbox Code Playgroud)

pandas._libs.ops.scalar_compare TypeError中的文件“ pandas_libs \ ops.pyx”,行98,TypeError:'str'和'int实例之间不支持'<='

我认为这与将负数视为字符串而不是float / int的函数有关,但是我尝试了以下代码来更正此错误,并且它什么都不会改变。任何帮助,将不胜感激。

test['sentiment_score'] = test['sentiment_score'].astype(float)
test['sentiment_score'] = test['sentiment_score'].apply(pd.as_numeric)
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 5

正如roganjosh所指出的,您要分3步进行替换-这会引起问题,因为在第1步之后,您将得到一列混合dtypes,因此后续的相等性检查开始失败。

您可以分配给新列,也可以使用numpy.select。

condlist = [
   test['sentiment_score'] > 0,
   test['sentiment_score'] < 0
]
choicelist = ['pos', 'neg']

test['sentiment_score'] = np.select(
   condlist, choicelist, default='neutral')
Run Code Online (Sandbox Code Playgroud)