在numpy数组中插入NaN值

Pet*_*ter 54 python interpolation numpy nan

是否有一种快速的方法用(例如)线性插值替换numpy数组中的所有NaN值?

例如,

[1 1 1 nan nan 2 2 nan 0]
Run Code Online (Sandbox Code Playgroud)

将被转换成

[1 1 1 1.3 1.6 2 2  1  0]
Run Code Online (Sandbox Code Playgroud)

eat*_*eat 90

让我们首先定义一个简单的辅助函数,以便更简单地处理NaN的索引和逻辑索引:

import numpy as np

def nan_helper(y):
    """Helper to handle indices and logical indices of NaNs.

    Input:
        - y, 1d numpy array with possible NaNs
    Output:
        - nans, logical indices of NaNs
        - index, a function, with signature indices= index(logical_indices),
          to convert logical indices of NaNs to 'equivalent' indices
    Example:
        >>> # linear interpolation of NaNs
        >>> nans, x= nan_helper(y)
        >>> y[nans]= np.interp(x(nans), x(~nans), y[~nans])
    """

    return np.isnan(y), lambda z: z.nonzero()[0]
Run Code Online (Sandbox Code Playgroud)

现在nan_helper(.)可以使用如下:

>>> y= array([1, 1, 1, NaN, NaN, 2, 2, NaN, 0])
>>>
>>> nans, x= nan_helper(y)
>>> y[nans]= np.interp(x(nans), x(~nans), y[~nans])
>>>
>>> print y.round(2)
[ 1.    1.    1.    1.33  1.67  2.    2.    1.    0.  ]
Run Code Online (Sandbox Code Playgroud)

---
虽然指定一个单独的函数来做这样的事情似乎有点过分了:

>>> nans, x= np.isnan(y), lambda z: z.nonzero()[0]
Run Code Online (Sandbox Code Playgroud)

它最终会带来红利.

因此,无论何时使用NaNs相关数据,只需在一些特定的辅助函数下封装所需的所有(新的NaN相关)功能.您的代码库将更加连贯和可读,因为它遵循易于理解的习语.

实际上,插值是观察NaN处理是如何完成的一个很好的上下文,但是在各种其他环境中也使用了类似的技术.

  • 如果可以的话,我会给你更多的支持! (2认同)

Pet*_*ter 22

我想出了这段代码:

import numpy as np
nan = np.nan

A = np.array([1, nan, nan, 2, 2, nan, 0])

ok = -np.isnan(A)
xp = ok.ravel().nonzero()[0]
fp = A[-np.isnan(A)]
x  = np.isnan(A).ravel().nonzero()[0]

A[np.isnan(A)] = np.interp(x, xp, fp)

print A
Run Code Online (Sandbox Code Playgroud)

它打印

 [ 1.          1.33333333  1.66666667  2.          2.          1.          0.        ]
Run Code Online (Sandbox Code Playgroud)

  • @fmonegaglia,不幸的是,该脚本仅在2D数组的一个轴上进行插值,而不是2D插值。需要在2N数组中的NaN上进行插值存在一个严重的问题:https://github.com/scipy/scipy/issues/1682 (3认同)
  • 将〜替换为〜以使其起作用(版本可能会随时间变化) (2认同)

小智 9

只需使用numpy逻辑和where where语句来应用1D插值.

import numpy as np
from scipy import interpolate

def fill_nan(A):
    '''
    interpolate to fill nan values
    '''
    inds = np.arange(A.shape[0])
    good = np.where(np.isfinite(A))
    f = interpolate.interp1d(inds[good], A[good],bounds_error=False)
    B = np.where(np.isfinite(A),A,f(inds))
    return B
Run Code Online (Sandbox Code Playgroud)

  • 这不会在序列的开头或结尾处理NaN. (2认同)

Gil*_*lly 7

对于二维数据,SciPygriddata对我来说效果很好:

>>> import numpy as np
>>> from scipy.interpolate import griddata
>>>
>>> # SETUP
>>> a = np.arange(25).reshape((5, 5)).astype(float)
>>> a
array([[  0.,   1.,   2.,   3.,   4.],
       [  5.,   6.,   7.,   8.,   9.],
       [ 10.,  11.,  12.,  13.,  14.],
       [ 15.,  16.,  17.,  18.,  19.],
       [ 20.,  21.,  22.,  23.,  24.]])
>>> a[np.random.randint(2, size=(5, 5)).astype(bool)] = np.NaN
>>> a
array([[ nan,  nan,  nan,   3.,   4.],
       [ nan,   6.,   7.,  nan,  nan],
       [ 10.,  nan,  nan,  13.,  nan],
       [ 15.,  16.,  17.,  nan,  19.],
       [ nan,  nan,  22.,  23.,  nan]])
>>>
>>> # THE INTERPOLATION
>>> x, y = np.indices(a.shape)
>>> interp = np.array(a)
>>> interp[np.isnan(interp)] = griddata(
...     (x[~np.isnan(a)], y[~np.isnan(a)]), # points we know
...     a[~np.isnan(a)],                    # values we know
...     (x[np.isnan(a)], y[np.isnan(a)]))   # points to interpolate
>>> interp
array([[ nan,  nan,  nan,   3.,   4.],
       [ nan,   6.,   7.,   8.,   9.],
       [ 10.,  11.,  12.,  13.,  14.],
       [ 15.,  16.,  17.,  18.,  19.],
       [ nan,  nan,  22.,  23.,  nan]])
Run Code Online (Sandbox Code Playgroud)

我在 3D 图像上使用它,在 2D 切片(350x350 的 4000 个切片)上运行。整个操作仍然需要大约一个小时:/


Win*_*ert 5

首先可能更容易更改数据的生成方式,但如果不是:

bad_indexes = np.isnan(data)
Run Code Online (Sandbox Code Playgroud)

创建一个布尔数组,指示nans的位置

good_indexes = np.logical_not(bad_indexes)
Run Code Online (Sandbox Code Playgroud)

创建一个布尔数组,指示好值区域的位置

good_data = data[good_indexes]
Run Code Online (Sandbox Code Playgroud)

原始数据的限制版本,不包括nans

interpolated = np.interp(bad_indexes.nonzero(), good_indexes.nonzero(), good_data)
Run Code Online (Sandbox Code Playgroud)

通过插值运行所有坏索引

data[bad_indexes] = interpolated
Run Code Online (Sandbox Code Playgroud)

用插值替换原始数据.

  • @Ben,对不起,我现在不能/不能测试它。尝试在两个非零 () 之后添加 [0]。 (2认同)

BBD*_*Sys 5

或者以温斯顿的回答为基础

def pad(data):
    bad_indexes = np.isnan(data)
    good_indexes = np.logical_not(bad_indexes)
    good_data = data[good_indexes]
    interpolated = np.interp(bad_indexes.nonzero()[0], good_indexes.nonzero()[0], good_data)
    data[bad_indexes] = interpolated
    return data

A = np.array([[1, 20, 300],
              [nan, nan, nan],
              [3, 40, 500]])

A = np.apply_along_axis(pad, 0, A)
print A
Run Code Online (Sandbox Code Playgroud)

结果

[[   1.   20.  300.]
 [   2.   30.  400.]
 [   3.   40.  500.]]
Run Code Online (Sandbox Code Playgroud)


nlm*_*lml 5

我需要一种在数据的开头和结尾处填充 NaN 的方法,但主要答案似乎没有这样做。

我想出的函数使用线性回归来填充 NaN。这解决了我的问题:

import numpy as np

def linearly_interpolate_nans(y):
    # Fit a linear regression to the non-nan y values

    # Create X matrix for linreg with an intercept and an index
    X = np.vstack((np.ones(len(y)), np.arange(len(y))))
    
    # Get the non-NaN values of X and y
    X_fit = X[:, ~np.isnan(y)]
    y_fit = y[~np.isnan(y)].reshape(-1, 1)
    
    # Estimate the coefficients of the linear regression
    beta = np.linalg.lstsq(X_fit.T, y_fit)[0]
    
    # Fill in all the nan values using the predicted coefficients
    y.flat[np.isnan(y)] = np.dot(X[:, np.isnan(y)].T, beta)
    return y
Run Code Online (Sandbox Code Playgroud)

这是一个示例用例:

# Make an array according to some linear function
y = np.arange(12) * 1.5 + 10.

# First and last value are NaN
y[0] = np.nan
y[-1] = np.nan

# 30% of other values are NaN
for i in range(len(y)):
    if np.random.rand() > 0.7:
        y[i] = np.nan
        
# NaN's are filled in!
print (y)
print (linearly_interpolate_nans(y))
Run Code Online (Sandbox Code Playgroud)


Pie*_*eux 5

我使用插值来替换所有 NaN 值。

A = np.array([1, nan, nan, 2, 2, nan, 0])
np.interp(np.arange(len(A)), 
          np.arange(len(A))[np.isnan(A) == False], 
          A[np.isnan(A) == False])
Run Code Online (Sandbox Code Playgroud)

输出 :

array([1. , 1.33333333, 1.66666667, 2. , 2. , 1. , 0. ])
Run Code Online (Sandbox Code Playgroud)