在2D数组上滚动窗口,作为1D数组,嵌套数组作为数据值

2024-04-18 16:31:16 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用np.lib.stride_tricks.as_strided时,如何管理以嵌套数组作为数据值的2D数组?是否有更好的有效的方法?在

具体来说,如果我有一个2D np.array如下所示,其中1D数组中的每个数据项都是一个长度为2的数组:

[[1., 2.],[3., 4.],[5.,6.],[7.,8.],[9.,10.]...]

我想对翻滚进行整形,如下所示:

^{pr2}$

我已经看过类似的答案(例如this rolling window function),但是在使用中,我不能让内部数组/元组保持不变。在

例如,{cd6}长度为{cd6}的

干杯。在


编辑:使用Python内置组件很容易生成功能相同的解决方案(可以使用类似于Divakar解决方案的np.arange进行优化),但是,使用as_strided如何?据我所知,这可能是一个高效的解决方案?在


Tags: 数据方法答案libasnp数组解决方案
3条回答

您的任务类似于this one。所以我稍微改了一下。在

# Rolling window for 2D arrays in NumPy
import numpy as np

def rolling_window(a, shape):  # rolling window for 2D array
    s = (a.shape[0] - shape[0] + 1,) + (a.shape[1] - shape[1] + 1,) + shape
    strides = a.strides + a.strides
    return np.lib.stride_tricks.as_strided(a, shape=s, strides=strides)

x = np.array([[1,2],[3,4],[5,6],[7,8],[9,10],[3,4],[5,6],[7,8],[11,12]])
y = np.array([[3,4],[5,6],[7,8]])
found = np.all(np.all(rolling_window(x, y.shape) == y, axis=2), axis=2)
print(found.nonzero()[0])

你的as_strided试验出了什么问题?对我有用。在

In [28]: x=np.arange(1,11.).reshape(5,2)
In [29]: x.shape
Out[29]: (5, 2)
In [30]: x.strides
Out[30]: (16, 8)
In [31]: np.lib.stride_tricks.as_strided(x,shape=(3,3,2),strides=(16,16,8))
Out[31]: 
array([[[  1.,   2.],
        [  3.,   4.],
        [  5.,   6.]],

       [[  3.,   4.],
        [  5.,   6.],
        [  7.,   8.]],

       [[  5.,   6.],
        [  7.,   8.],
        [  9.,  10.]]])

在我的第一次编辑中,我使用了一个int数组,因此必须使用(8,8,4)来实现跨步。在

你的形状可能不对。如果太大,它开始看到数据缓冲区末尾的值。在

^{pr2}$

这里它只是改变了显示方法,7, 8, 9, 10仍然存在。编写那些插槽可能很危险,会弄乱代码的其他部分。as_strided最好用于只读目的。写入/设置更为棘手。在

你可以这样做-

def rolling_window2D(a,n):
    # a: 2D Input array 
    # n: Group/sliding window length
    return a[np.arange(a.shape[0]-n+1)[:,None] + np.arange(n)]

样本运行-

^{pr2}$

相关问题 更多 >