首页 > 解决方案 > Python 舍入值不适用于 Numpy 条件产生 TypeError: '<' not supported between 'list' 和 'float

问题描述

我遇到在数组中将某个阈值(22.0)舍入为 0 时 numpy 条件不起作用的情况。numpy 条件的第二个选项rainB[np.where(rainB<threshold)]=0.0也不起作用。结果显示;TypeError: '<' not supported between instances of 'list' and 'float'. 有人有想法吗?谢谢

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)

    rainB[rainB < threshold] = 0.0
    ##rainB[np.where(rainB<threshold)]=0.0

标签: pythonroundingnumpy-ndarray

解决方案


问题是它rainB是一个列表而不是一个 numpy 数组,但您正试图将它与 numpy 工具一起使用。您可以使用 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]

arr = np.array(temp_new)
rainB = np.where(arr <= 185, np.interp(temp_new, tempA, rainA), 0.2 * arr + 0.7)
rainB[rainB < threshold] = 0.0

print(rainB)

它给:

[41.416      38.14       29.89289286 37.9       ]

推荐阅读