计算滚动的零-numpy数组(包括NaN)

问题描述 投票:0回答:1

我正在尝试找到一种使用numpy数组滚动计算零的方法?

使用熊猫,我可以使用:

df['demand'].apply(lambda x: (x == 0).rolling(7).sum()).fillna(0))

df['demand'].transform(lambda x: x.rolling(7).apply(lambda x: 7 - np.count _nonzero(x))).fillna(0)

在numpy中,使用Here中的代码

def rolling_window(a, window_size):
    shape = (a.shape[0] - window_size + 1, window_size) + a.shape[1:]
    print(shape)
    strides = (a.strides[0],) + a.strides
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

arr = np.asarray([10, 20, 30, 5, 6, 0, 0, 0])

np.count_nonzero(rolling_window(arr==0, 7), axis=1)

Output:
    array([2, 3])

但是,我也需要前6个NaN,并用零填充:

预期输出:

array([0, 0, 0, 0, 0, 0, 2, 3])
pandas numpy
1个回答
0
投票

我将对功能进行如下修改:

def count_rolling(a, window_size):
    shape = (a.shape[0] - window_size + 1, window_size) + a.shape[1:]

    strides = (a.strides[0],) + a.strides
    rolling = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

    out = np.zeros_like(a)
    out[window_size-1:] = (rolling == 0).sum(1)
    return out

arr = np.asarray([10, 20, 30, 5, 6, 0, 0, 0])
count_rolling(arr,7)

输出:

array([0, 0, 0, 0, 0, 0, 2, 3])
© www.soinside.com 2019 - 2024. All rights reserved.