numpy.recarray.strides#
属性
- recarray.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)