You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:48:01