从numpy数组中获取具有给定步幅/步长的子数组 [英] Taking subarrays from numpy array with given stride/stepsize
本文介绍了从numpy数组中获取具有给定步幅/步长的子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有一个Python Numpy数组a
.
Lets say I have a Python Numpy array a
.
a = numpy.array([1,2,3,4,5,6,7,8,9,10,11])
我想从步长为3的长度为5的数组创建一个子序列矩阵,结果矩阵如下所示:
I want to create a matrix of sub sequences from this array of length 5 with stride 3. The results matrix hence will look as follows:
numpy.array([[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,11]])
实现此目标的一种可能方法是使用for循环.
One possible way of implementing this would be using a for-loop.
result_matrix = np.zeros((3, 5))
for i in range(0, len(a), 3):
result_matrix[i] = a[i:i+5]
在Numpy中有没有更干净的方法来实现这一点?
Is there a cleaner way to implement this in Numpy?
推荐答案
方法1:使用 方法2::使用更有效的 NumPy strides
-
Approach #2 : Using more efficient NumPy strides
-
def strided_app(a, L, S ): # Window len = L, Stride len/stepsize = S
nrows = ((a.size-L)//S)+1
n = a.strides[0]
return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))
样品运行-
In [143]: a
Out[143]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
In [144]: broadcasting_app(a, L = 5, S = 3)
Out[144]:
array([[ 1, 2, 3, 4, 5],
[ 4, 5, 6, 7, 8],
[ 7, 8, 9, 10, 11]])
In [145]: strided_app(a, L = 5, S = 3)
Out[145]:
array([[ 1, 2, 3, 4, 5],
[ 4, 5, 6, 7, 8],
[ 7, 8, 9, 10, 11]])
这篇关于从numpy数组中获取具有给定步幅/步长的子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文