numpy.ndarray.strides#
屬性
- ndarray.strides#
遍歷陣列時,在每個維度中步進的位元組元組。
陣列 a 中元素
(i[0], i[1], ..., i[n])
的位元組偏移量為offset = sum(np.array(i) * a.strides)
關於 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 個位元組,一個接一個(稱為連續的記憶體區塊)。陣列的 strides 告訴我們,為了沿著特定軸移動到下一個位置,我們必須在記憶體中跳過多少位元組。例如,我們必須跳過 4 個位元組(1 個值)才能移動到下一列,但要跳過 20 個位元組(5 個值)才能到達下一欄中的相同位置。因此,陣列 x 的 strides 將為
(20, 4)
。範例
>>> import numpy as np >>> y = np.reshape(np.arange(2*3*4), (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]]]) >>> y.strides (48, 16, 4) >>> y[1,1,1] 17 >>> offset=sum(y.strides * np.array((1,1,1))) >>> offset/y.itemsize 17
>>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0) >>> x.strides (32, 4, 224, 1344) >>> i = np.array([3,5,2,2]) >>> offset = sum(i * x.strides) >>> x[3,5,2,2] 813 >>> offset / x.itemsize 813