python - 从具有给定步幅/步长的 numpy 数组中获取子数组

标签 python numpy vectorization

假设我有一个 Python Numpy 数组 a.

a = numpy.array([1,2,3,4,5,6,7,8,9,10,11])

我想从这个长度为 5、步长为 3 的数组创建一个子序列矩阵。因此结果矩阵如下所示:

numpy.array([[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,11]])

一种可能的实现方式是使用 for 循环。

result_matrix = np.zeros((3, 5))
for i in range(0, len(a), 3):
  result_matrix[i] = a[i:i+5]

在 Numpy 中是否有更简洁的方法来实现这一点?

最佳答案

方法 #1: 使用 broadcasting -

def broadcasting_app(a, L, S ):  # Window len = L, Stride len/stepsize = S
    nrows = ((a.size-L)//S)+1
    return a[S*np.arange(nrows)[:,None] + np.arange(L)]

方法 #2: 使用更高效的 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]])

关于python - 从具有给定步幅/步长的 numpy 数组中获取子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40084931/

相关文章:

python - numpy中的插入排序?

Python - 计算 word2vec 向量的层次聚类并将结果绘制为树状图

c# - 读取旋转日志文件和文件锁定

python - 如何使用 Robot Framework 从测试套件运行特定的测试用例

python - 艰难地学习 Python 练习 13 错误

nlp - gensim 如何计算 doc2vec 段落向量

python - 将数组元素的邻居广义堆叠到 3D 数组中

python - 替换列表中的所有负值

python - 仅使用 numpy 最大池化 2x2 数组

performance - 如何有效地创建两个向量中所有值对的热图?