TypeError:&不支持的操作数类型:使用np.select的'str'和'bool'

时间:2019-08-02 12:47:16

标签: pandas numpy

尝试将np.selelct与以下代码一起使用时,我得到@ColumnInfo(name = "state_of_health") @TypeConverters(HealthConverter::class) var health: Health enum class Health(val value: Int){ NONE(-1), VERY_BAD(0), ... } class HealthConverter{ @TypeConverter fun fromHealth(value: Health): Int{ return value.ordinal } @TypeConverter fun toHealth(value: Int): Health{ return when(value){ -1 -> Health.NONE 0 -> Health.VERY_BAD ... else -> Health.EXCELLENT } } }

TypeError: unsupported operand type(s) for &: 'str' and 'bool'

1 个答案:

答案 0 :(得分:1)

通过boolean indexing创建布尔掩码列表,插入过滤后的DataFrame列表:

df = pd.DataFrame({
         'RATING_BASE_AMT':[4,1000,999,1001,2000,2001],
})

将值转换为数字:

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

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

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