不适用于 Numpy 条件的 Python 舍入值会产生类型错误:'list' 和 'float 的实例之间不支持'<'



我有numpy条件不工作时,四舍五入一些阈值(22.0)到0在数组中。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

问题是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       ]

这里可以使用列表推导式:

rainB = [0 if x < threshold else x for x in rainB]

查看列表推导式中的if/else。

相关内容

最新更新