np.lib.stride_tricks.as_strided函数的一点理解

题目及代码来自numpy100:https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_hints_with_solutions.md#42-consider-two-random-array-a-and-b-check-if-they-are-equal-

76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (★★★)

hint: from numpy.lib import stride_tricks

# Author: Joe Kington / Erik Rigtorp
from numpy.lib import stride_tricks

def rolling(a, window):
    shape = (a.size - window + 1, window)
    strides = (a.itemsize, a.itemsize)
    return stride_tricks.as_strided(a, shape=shape, strides=strides)
Z = rolling(np.arange(10,dtype=np.int32), 3)
print(Z)

shape 为变形后的形状;
strides中各个数字为每一“步”的字节数,每一组内的间隔是1(数据类型int32为4字节),组与组件的间隔也是1(4字节),故而strides为(4,4)
(趁着还有印象赶快写下来。。。)
Ref:
https://zhuanlan.zhihu.com/p/64933417

你可能感兴趣的:(np.lib.stride_tricks.as_strided函数的一点理解)