Python使用Numpy条件赋值阈值置0时报list与float比较TypeError如何解决
问题原因
- 你声明的
rainB为Python原生列表类型,Numpy的布尔索引、np.where等数组操作仅支持Numpy数组类型,原生列表不支持直接和浮点数做大小比较,因此触发类型错误。 - 你将条件赋值的代码放在了for循环内部,此时每轮循环仅向
rainB中添加了一个元素,尚未完成全部数值的计算,即使转换为数组也不符合业务逻辑要求。
修复方案
先完成所有元素的计算填充,再将rainB转换为Numpy数组后执行条件赋值即可,修正后代码如下:
import numpy as np tempA = [183.650, 185.050, 185.250, 188.550] rainA = [41.416, 16.597, 20.212, 30.029] threshold = 22.0 temp_new = [183.110, 187.20, 184.30, 186.0] rainB = [] for x in temp_new: if x <= 185.0: rain1 = np.interp(x, tempA, rainA) else: rain1 = 0.2 * x + 0.7 rainB.append(rain1) # 转为Numpy数组后执行条件赋值 rainB = np.array(rainB) rainB[rainB < threshold] = 0.0 # 你也可以用np.where写法,效果一致 # rainB = np.where(rainB < threshold, 0.0, rainB)
内容的提问来源于stack exchange,提问作者Azam
相关产品推荐
相关产品推荐

