有没有一种快速的方法可以用(比方说)线性插值的值替换NaN数组中的所有numpy值?
例如,
[1 1 1 nan nan 2 2 nan 0]
将被转换为
[1 1 1 1.3 1.6 2 2 1 0]
发布于 2011-06-29 12:34:30
让我们首先定义一个简单的助手函数,以便更直接地处理NaNs的索引和逻辑索引
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]
现在可以像这样使用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. ]
-
尽管首先指定一个单独的函数来做这样的事情可能看起来有点夸张:
>>> nans, x= np.isnan(y), lambda z: z.nonzero()[0]
它最终会带来红利。
因此,每当您使用与NaN相关的数据时,只需将所需的所有(新的与NaN相关的)功能封装在某个特定的帮助器函数下。您的代码库将更加连贯和可读性更好,因为它遵循易于理解的习惯用法。
实际上,插值是一个很好的上下文来查看NaN处理是如何完成的,但类似的技术也可以在各种其他上下文中使用。
发布于 2011-06-29 10:19:57
我想出了这个代码:
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
它打印出来
[ 1. 1.33333333 1.66666667 2. 2. 1. 0. ]
发布于 2012-03-22 02:11:29
只需使用numpy逻辑and where语句来应用一维插值。
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
https://stackoverflow.com/questions/6518811
复制