10

这是我的代码:

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

我怎样才能在没有循环的情况下仅使用's 工具nan向我的数组添加 20 次?numpynumpy

谢谢

4

3 回答 3

18
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.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

But np.append is quicker:

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

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 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
于 2013-10-23T10:48:17.120 回答
2
n = np.hstack((n, np.zeros(20) + np.nan))
于 2013-10-23T10:43:43.250 回答
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)
于 2020-12-02T09:02:07.157 回答