numpy.ndarray.strides#

属性

ndarray.strides#

在遍历数组时,每个维度中步进的字节元组。

数组 a 中元素 (i[0], i[1], ..., i[n]) 的字节偏移量是

offset = sum(np.array(i) * a.strides)

关于步长更详细的解释可以在 N 维数组 (ndarray) 中找到。

警告

不建议设置 arr.strides,未来可能会弃用。应优先使用 numpy.lib.stride_tricks.as_strided 以更安全的方式创建相同数据的新视图。

注释

假设有一个 32 位整数数组(每个 4 字节)

x = np.array([[0, 1, 2, 3, 4],
              [5, 6, 7, 8, 9]], dtype=np.int32)

此数组在内存中存储为 40 个字节,一个接一个(称为连续内存块)。数组的步长告诉我们沿着某个轴移动到下一个位置需要在内存中跳过多少字节。例如,我们必须跳过 4 个字节(1 个值)才能移动到下一列,但要跳过 20 个字节(5 个值)才能到达下一行中的相同位置。因此,数组 x 的步长将是 (20, 4)

示例

>>> import numpy as np
>>> y = np.reshape(np.arange(2 * 3 * 4, dtype=np.int32), (2, 3, 4))
>>> y
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],
       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]], dtype=np.int32)
>>> y.strides
(48, 16, 4)
>>> y[1, 1, 1]
np.int32(17)
>>> offset = sum(y.strides * np.array((1, 1, 1)))
>>> offset // y.itemsize
np.int64(17)
>>> x = np.reshape(np.arange(5*6*7*8, dtype=np.int32), (5, 6, 7, 8))
>>> x = x.transpose(2, 3, 1, 0)
>>> x.strides
(32, 4, 224, 1344)
>>> i = np.array([3, 5, 2, 2], dtype=np.int32)
>>> offset = sum(i * x.strides)
>>> x[3, 5, 2, 2]
np.int32(813)
>>> offset // x.itemsize
np.int64(813)