2016-12-14 17 views
1

其中“缺席”可以表示nannp.masked,取其中最容易实现的值。如何有效地“拉伸”数组中的当前值而不使用缺省值

例如:

>>> from numpy import nan 
>>> do_it([1, nan, nan, 2, nan, 3, nan, nan, 4, 3, nan, 2, nan]) 
array([1, 1, 1, 2, 2, 3, 3, 3, 4, 3, 3, 2, 2]) 
# each nan is replaced with the first non-nan value before it 
>>> do_it([nan, nan, 2, nan]) 
array([nan, nan, 2, 2]) 
# don't care too much about the outcome here, but this seems sensible 

我可以看到你是如何做到这一点有一个for循环:

def do_it(a): 
    res = [] 
    last_val = nan 
    for item in a: 
     if not np.isnan(item): 
      last_val = item 
     res.append(last_val) 
    return np.asarray(res) 

是否有向量化它更快的方法?

回答

1

从@本杰明的删除解决方案时,一切都很好,如果你与指数

def do_it(data, valid=None, axis=0): 
    # normalize the inputs to match the question examples 
    data = np.asarray(data) 
    if valid is None: 
     valid = ~np.isnan(data) 

    # flat array of the data values 
    data_flat = data.ravel() 

    # array of indices such that data_flat[indices] == data 
    indices = np.arange(data.size).reshape(data.shape) 

    # thanks to benjamin here 
    stretched_indices = np.maximum.accumulate(valid*indices, axis=axis) 
    return data_flat[stretched_indices] 

比较的解决方案运行时的工作:

>>> import numpy as np 
>>> data = np.random.rand(10000) 

>>> %timeit do_it_question(data) 
10000 loops, best of 3: 17.3 ms per loop 
>>> %timeit do_it_mine(data) 
10000 loops, best of 3: 179 µs per loop 
>>> %timeit do_it_user(data) 
10000 loops, best of 3: 182 µs per loop 

# with lots of nans 
>>> data[data > 0.25] = np.nan 

>>> %timeit do_it_question(data) 
10000 loops, best of 3: 18.9 ms per loop 
>>> %timeit do_it_mine(data) 
10000 loops, best of 3: 177 µs per loop 
>>> %timeit do_it_user(data) 
10000 loops, best of 3: 231 µs per loop 

因此,无论这一点,并@ user2357112的解决方案吹的解决方案问题出在水面上,但是当有大量的nan s时,这比@ user2357112略有优势

1

cumsum明过的标志的阵列提供了一个很好的方法,以确定在所述的NaN写哪些号码:

def do_it(x): 
    x = np.asarray(x) 

    is_valid = ~np.isnan(x) 
    is_valid[0] = True 

    valid_elems = x[is_valid] 
    replacement_indices = is_valid.cumsum() - 1 
    return valid_elems[replacement_indices] 
+0

嗯,如果x是2d,这不起作用,但我想这不是我所要求的 – Eric

+0

@Eric:是的,我不知道你甚至想要2D输入。 – user2357112

+0

我希望它可以独立处理每一行,就像它是1d一样 – Eric

1

假设有在数据没有零点(为了使用numpy.nan_to_num):

b = numpy.maximum.accumulate(numpy.nan_to_num(a)) 
>>> array([ 1., 1., 1., 2., 2., 3., 3., 3., 4., 4.]) 
mask = numpy.isnan(a) 
a[mask] = b[mask] 
>>> array([ 1., 1., 1., 2., 2., 3., 3., 3., 4., 3.]) 

编辑:正如埃里克,指出了一个更好的解决方案是-inf取代的NaN:

mask = numpy.isnan(a) 
a[mask] = -numpy.inf 
b = numpy.maximum.accumulate(a) 
a[mask] = b[mask] 
+0

不错!用'-inf'代替'nan'也可以在这里工作,对吧? – Eric

+0

@Eric:的确,更好的解决方案。 – Benjamin

+0

等一下,这是行不通的。看到我更新的测试用例。你认为这些数值总是在增加,他们不是 – Eric