簡體   English   中英

在scipy中內插np.nan值

[英]Interpolating np.nan values in scipy

我想通過插入以粗體顯示的元素來填充np.nan數據值。 它們是在其他維度上與np.nan的相同位置相對應的元素。

import numpy as np
from scipy.interpolate import interp1d
data = np.array([[[3, 2, 1, 3, 2],
                  [**np.nan**, 1, 1, 4, 4],
                  [4, 2, 3, 3, 4],
                  [1, 1, 4, 1, 5],
                  [2, 4, 5, 2, 1]],

                 [[6, 7, 10, 6, 6],
                  [**5**, 9, 8, 6, 9],
                  [6, 10, 9, 8, 10],
                  [6, 8, 7, 10, 8],
                  [10, 9, 9, 10, 8]],

                 [[12, 14, 12, 15, 15],
                  [**21**, 11, 14, 14, 11],
                  [13, 13, 16, 15, 11],
                  [14, 15, 14, 16, 14],
                  [13, 15, 11, 11, 14]]])

result = interp1d(data, kind='cubic')
print result

結果

TypeError: __init__() takes at least 3 arguments (3 given)

最好的方法是什么? 由於我必須處理非常大的數組,因此我正在尋找有效的方法。

您的問題太籠統了,插值不需要5 * 5矩陣中的任何信息,只需其他維度中同一單元格中的值即可? 如果是這樣的話,那就太麻煩了,因為有太多的插值工具無法滿足不同的需求。 我會說,盡管scipy.interpolate的文檔在某些方面有些薄弱,但也許最鄰近的方法應該為您提供一個良好的開端。

In [1]:

data = np.array([[[3, 2, 1, 3, 2],
                  [np.nan, 1, 1, 4, 4],
                  [4, 2, 3, 3, 4],
                  [1, 1, 4, 1, 5],
                  [2, 4, 5, 2, 1]],

                 [[6, 7, 10, 6, 6],
                  [5, 9, 8, 6, 9],
                  [6, 10, 9, 8, 10],
                  [6, 8, 7, 10, 8],
                  [10, 9, 9, 10, 8]],

                 [[12, 14, 12, 15, 15],
                  [21, 11, 14, 14, 11],
                  [13, 13, 16, 15, 11],
                  [14, 15, 14, 16, 14],
                  [13, 15, 11, 11, 14]]])
In [2]:

data1=data.reshape((3,-1))
In [3]:
#the one you want to interpolate
data1[:,(np.isnan(data.reshape((3,-1))).any(0))]
Out[3]:
array([[ nan],
       [  5.],
       [ 21.]])
In [4]:
#the other 'good' data points
data1[:,~(np.isnan(data.reshape((3,-1))).any(0))]
Out[4]:
array([[  3.,   2.,   1.,   3.,   2.,   1.,   1.,   4.,   4.,   4.,   2.,
          3.,   3.,   4.,   1.,   1.,   4.,   1.,   5.,   2.,   4.,   5.,
          2.,   1.],
       [  6.,   7.,  10.,   6.,   6.,   9.,   8.,   6.,   9.,   6.,  10.,
          9.,   8.,  10.,   6.,   8.,   7.,  10.,   8.,  10.,   9.,   9.,
         10.,   8.],
       [ 12.,  14.,  12.,  15.,  15.,  11.,  14.,  14.,  11.,  13.,  13.,
         16.,  15.,  11.,  14.,  15.,  14.,  16.,  14.,  13.,  15.,  11.,
         11.,  14.]])
In [5]:

import scipy.interpolate as si
In [6]:

Q=si.NearestNDInterpolator(data1[:,~(np.isnan(data.reshape((3,-1))).any(0))][[1,2]].T, 
                           data1[:,~(np.isnan(data.reshape((3,-1))).any(0))][0])
In [8]:
#the first value is the answer, the 2nd is the index of the nearest neighbor.
Q.tree.query([5,21])
Out[8]:
(6.082762530298219, 3) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM