python - 如何从 numpy 中的 dtype 获取步幅?

标签 python numpy stride

我想我可以: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/

相关文章:

opengl-es - 跨步在OpenGL | ES中是什么意思

python - 从 google.cloud.logging_v2 导入类型 ImportError : cannot import name types

python - 仅在检测到的对象内检测文本

python - 如何根据 sqlalchemy 中 child 的某些属性对对象进行排序?

python - 向量化 numpy 对于子数组是唯一的

Python 字符串切片步幅说明

python - 在 python () 中查找作为集合数组成员的数组元素

python - 代码优化——Python中的函数调用次数

python - 错误消息缺少必需的依赖项,导入错误 : Missing required dependencies ['numpy' ] when I try and freeze an executable

Swift 2.2 递减特定于 Swift 3 中的循环