在没有循环的情况下将“nan”添加到numpy数组20次

时间:2013-10-23 10:33:58

标签: python arrays numpy

这是我的代码:

import numpy as np
n = np.array([1.1,2.3,3.4])
for x in range(20):
    n = np.append(n, [np.nan])

如何在没有循环的情况下将nan添加到numpy数组20次,只使用numpy的工具?

由于

3 个答案:

答案 0 :(得分:10)

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

[编辑] 好吧,使用np.repeat似乎比使用Mr E’s answer中的np.zeros(20) + np.nan更慢:

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

In [2]: timeit np.repeat(np.nan, 10000)
10000 loops, best of 3: 70.8 µs per loop

但是np.append更快:

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

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

所以你可以结合两种方法:

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

这给出了:

In [42]: timeit np.hstack((n, np.zeros(20) + np.nan))
100000 loops, best of 3: 13.2 µs per loop

In [43]: timeit np.append(n, np.repeat(np.nan, 20))
100000 loops, best of 3: 15.4 µs per loop

In [44]: timeit np.append(n, np.zeros(20) + np.nan)
100000 loops, best of 3: 10.5 µs per loop

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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)