我想我可以:np.zeros((), dtype=dt).strides
,但是当 dtype 是大型数组类型时,这似乎效率不高,例如: ('<f8', (200, 100))
。有没有办法直接从 dtype 到 numpy 中的 strides?
最佳答案
您实际上可以获取结构化数组中子数组的步幅,而无需创建“完整”数组。
结构化数组中的子数组必须是连续的且按 C 顺序 according to the documentation 。请注意第一个示例上方的句子:
Sub-arrays always have a C-contiguous memory layout.
因此,对于没有字段的结构化数组(例如示例中的字段),您可以执行以下操作(作为不可读的单行代码):
import numpy as np
x = np.dtype(('<f8', (200, 100)))
strides = x.base.itemsize * np.r_[1, np.cumprod(x.shape[::-1][:-1])][::-1]
避免代码高尔夫:
shape = list(x.shape)
# First, let's make the strides for an array with an itemsize of 1 in C-order
tmp_strides = shape[::-1]
tmp_strides[1:] = list(np.cumprod(tmp_strides[:-1]))
tmp_strides[0] = 1
# Now adjust it for the real itemsize:
tmp_strides = x.base.itemsize * np.array(tmp_strides)
# And convert it to a tuple, reversing it back for proper C-order
strides = tuple(tmp_strides[::-1])
但是,当存在多个字段时,这会变得更加复杂。一般来说,您需要进行适当的检查。例如:dtype 是否具有 shape
属性?有字段吗?是否有任何字段具有 shape
属性?
关于python - 如何从 numpy 中的 dtype 获取步幅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32872743/