Add "nan" to numpy array 20 times without loop Add "nan" to numpy array 20 times without loop numpy numpy

Add "nan" to numpy array 20 times without loop


n = np.append(n, np.repeat(np.nan, 20))

[Edit]Ok, it seems that use of np.repeat is slower than use of np.zeros(20) + np.nan like in Mr E’s answer:

In [1]: timeit np.zeros(10000) + np.nan100000 loops, best of 3: 16.1 µs per loopIn [2]: timeit np.repeat(np.nan, 10000)10000 loops, best of 3: 70.8 µs per loop

But np.append is quicker:

In [3]: timeit np.append(n, n)100000 loops, best of 3: 5.56 µs per loopIn [4]: timeit np.hstack((n, n))100000 loops, best of 3: 7.87 µs per loop

So you can combine both approaches:

np.append(n, np.zeros(20) + np.nan)

This gives:

In [42]: timeit np.hstack((n, np.zeros(20) + np.nan))100000 loops, best of 3: 13.2 µs per loopIn [43]: timeit np.append(n, np.repeat(np.nan, 20))100000 loops, best of 3: 15.4 µs per loopIn [44]: timeit np.append(n, np.zeros(20) + np.nan)100000 loops, best of 3: 10.5 µs per loop


n = np.hstack((n, np.zeros(20) + np.nan))


def rolling_window(a, window, method, backfill_method='nan'):    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)    strides = a.strides + (a.strides[-1],)    toReturn = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)    if method == 'mean':         toReturn = np.mean(toReturn, 1)    elif method == 'std':        toReturn = np.std(toReturn, 1)    if backfill_method == 'nan':        first_valid = np.nan    elif backfill_method == 'first':        first_valid = toReturn[0]    return np.append(np.repeat(first_valid, len(a) - len(toReturn)), toReturn)