TypeError:&amp ;: np.select的'str'和'bool'不支持的操作数类型 [英] TypeError: unsupported operand type(s) for &: 'str' and 'bool' with np.select

查看:73
本文介绍了TypeError:&amp ;: np.select的'str'和'bool'不支持的操作数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试将np.selelct与以下代码一起使用时,我得到一个TypeError: unsupported operand type(s) for &: 'str' and 'bool'.

I'm getting a TypeError: unsupported operand type(s) for &: 'str' and 'bool' when trying to use np.selelct with the below code.

condition = [(tt_df.loc[tt_df['RATING_BASE_AMT'] <=1000])
,(tt_df.loc[tt_df['RATING_BASE_AMT'] > 1000] & tt_df.loc[tt_df['RATING_BASE_AMT'] <=2000]),
,(tt_df.loc[tt_df['RATING_BASE_AMT'] > 2000])]

replace = [1000, 2000, 3000]

df['model_value'] = np.select(condition, replace, default = 1)

推荐答案

通过将值转换为数字:

tt_df['RATING_BASE_AMT'] = tt_df['RATING_BASE_AMT'].astype(float)

或者如果可能的话,在列中输入一些非数字值:

Or if possible some non numeric values in column:

tt_df['RATING_BASE_AMT'] = pd.to_numeric(tt_df['RATING_BASE_AMT'], errors='coerce')


replace = [1000, 2000, 3000]
condition = [(df['RATING_BASE_AMT'] <=1000), 
             (df['RATING_BASE_AMT'] > 1000) & (df['RATING_BASE_AMT'] <=2000),
             (df['RATING_BASE_AMT'] > 2000)]

df['model_value'] = np.select(condition, replace, default = 1)

或使用 pd.cut :

df['model_value1'] = pd.cut(df['RATING_BASE_AMT'], 
                          bins=[-np.inf, 1000, 2000, np.inf], 
                          labels=[1000, 2000, 3000])

print (df)
   RATING_BASE_AMT  model_value model_value1
0                4         1000         1000
1             1000         1000         1000
2              999         1000         1000
3             1001         2000         2000
4             2000         2000         2000
5             2001         3000         3000

这篇关于TypeError:&amp ;: np.select的'str'和'bool'不支持的操作数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆