ZeroDivisionError:使用 scipy.interpolate.rbf('cubic") 浮动除以零

问题描述

我正在尝试使用 scipy 库,特别是 rbf('cubic') 来插入缺失值。但我收到以下错误

Traceback (most recent call last):
  File "C:\Users\St\Desktop\py_magn\inter.py",line 89,in <module>
    rbfp = Rbf(xn,yn,magn,function='cubic') #ParaMETERS
  File "C:\Users\St\AppData\Local\Programs\Python\python38\lib\site-packages\scipy\interpolate\rbf.py",line 239,in __init__
    self.epsilon = np.power(np.prod(edges)/self.N,1.0/edges.size)
ZeroDivisionError: float division by zero

我的代码如下:

x,y,mag = df[:,0],df[:,1],3]



emptyInd = np.where(np.isnan(mag))
print(emptyInd[0])
#----------------------------------------------------------------------------------------------------

def eucl_dist(pnt,x,mag):
    value = []
    dist = 0.0
    typ = [('Eucli dist',float),('x',('y',('Magn',float)]
    for i in range(len(x)):
        dist = sqrt((pnt[0]-x[i])**2 + (pnt[1]-y[i])**2)
        res = [dist,x[i],y[i],mag[i]]
        value.append(res)
    
    value = np.vstack(value)
    
    return value,typ

#--------------------------------------------------------------------------------

                    
xinter=[]
yinter=[]
magInter=[]
neigh = []
if len(emptyInd)!=0 :
    listofEMPval = list(zip(emptyInd[0])) #,emptyInd[1]))
    for ind in listofEMPval:
        xn=[]
        yn=[]
        magn=[]
        xinter = np.take(x,ind)
        yinter = np.take(y,ind)
        
        edist,typ = eucl_dist((xinter,yinter),mag)
        edist = rf.unstructured_to_structured(edist,np.dtype(typ))
        indx = np.argsort(edist,order='Eucli dist')
        edist = np.reshape([edist[i] for i in indx],(len(edist),1))
        
        sz=182
        for k in range(sz):
            if np.isnan(edist[k][0][3]):
                k+=1
                sz+=1
            else:
                xn = np.append(xn,edist[k][0][1])
                yn = np.append(yn,edist[k][0][2])
                magn = np.append(magn,edist[k][0][3])
           
        rbfp = Rbf(xn,function='cubic') #ParaMETERS
        magInter = np.append(magInter,rbfp(xinter,yinter)) #INTERPOLATION
        

    for i in range(len(listofEMPval)):
        np.put(mag,listofEMPval[i],magInter[i])
    

 

我考虑了用于插值的特定数量的数据点。另外,有没有其他方法可以让它更快? 谢谢

更新 正如我在“答案”部分所写的那样,我解决了我的问题。唯一剩下的想法是是否有任何方法可以使它更快。我认为问题是插值部分

解决方法

所以我意识到了这个问题并修复了它。在我的代码中,我计算了 nan 点(我想插值)和所有其他点之间的距离。起初我没有想到我的数据集中有这么多 nan 值,而且我认为每次我遇到一个“nan”值时,通过将变量的值增加 1,我在 for-选择插值点的循环(特别是:for i in range(nval): ),将保持插值点的数量。但它没有。所以我只是添加了以下代码以构建一个数组,该数组从排序列表中只保留带有值的点(不是 nan)

ex=[0,0]
for i in range(len(edist)):
    if np.isnan(edist[i][0][3])==False:
        ex=np.vstack((ex,[edist[i][0][1],edist[i][0][2],edist[i][0][3]]))
        
ex=ex[1:,:]