2013-05-03 42 views
2

我有一个包含各种大小缝隙的numpy阵列。我想用线性插值填充尺寸为< N的较小间隙。识别1D numpy阵列中的缝隙大小

换言之为:

N = 2 

x = np.array([10., 20., np.nan, 40., 50., np.nan, np.nan, np.nan, 10.,0.,-10.]) 

我想填充30.0第三(索引2)项。

我打开演算方法,但我的目的是创建一个数组,这将是当地的缝隙大小的指标:

[0 0 1 0 0 3 3 3 0 0] 

或间隙过大而:

[0 0 0 0 0 1 1 1 0 0] 

在手中,我可以记录足够小的间隙指标并使用interp1d有没有一种经济实用的方法来实现这一点?我知道如何用预先标记预先标记循环来完成。

感谢,

+0

因此,第一阵列中(' [0 0 1 0 0 3 3 3 0 0]')'1'和'3'表示没有“正确”数字的顺序元素的数量? – SethMMorton 2013-05-03 23:49:46

+0

恰好,SethMMorton。 – 2013-05-04 01:49:19

回答

0

我不知道,如果这是你在寻找什么,但是这是我的建议:

>>> import numpy as np 
>>> from itertools import groupby 
>>> 
>>> x = np.array([10., 20., np.nan, 40., 50., np.nan, np.nan, np.nan, 10.,0.,-10.]) 
>>> y = np.zeros_like(x, dtype=int) 
>>> y[np.where(np.isnan(x))] = 1 # Locate where the array is nan 
>>> y 
array([0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0]) 
>>> z = [] 
>>> for a, b in groupby(y, lambda x: x == 0): 
...  if a: # Where the value is 0, simply append to the list 
...   z.extend(list(b)) 
...  else: # Where the value is one, replace 1 with the number of sequential 1's 
...   l = len(list(b)) 
...   z.extend([l]*l) 
>>> z 
[0, 0, 1, 0, 0, 3, 3, 3, 0, 0, 0]