python - 将numpy数组转换为结构化数组

标签 python arrays python-3.x numpy structured-array

假设我有以下数组:

arr = np.array([[1,2], [3,4]], dtype='u1')
我想把它转换成这样的结构化数组:
strarr = np.array([(1,2), (3,4)], dtype=[('a', 'u1'), ('b', 'u1')])
如果我只是尝试
arr.astype([('a', 'u1'), ('b', 'u1')])
它返回
>>> array([[(1, 1), (2, 2)],
       [(3, 3), (4, 4)]], dtype=[('a', 'u1'), ('b', 'u1')])
如何转换数组以便它使用一行的所有元素来填充字段(前提是数字匹配)而不是复制每个元素?

最佳答案

为此有特殊的帮助函数:

>>> from numpy.lib.recfunctions import unstructured_to_structured
所以,
>>> import numpy as np
>>> arr = np.array([[1,2], [3,4]], dtype='u1')
>>> unstructured_to_structured(arr, dtype=np.dtype([('a', 'u1'), ('b', 'u1')]))
array([(1, 2), (3, 4)], dtype=[('a', 'u1'), ('b', 'u1')])
您还可以创建 View :
>>> arr.ravel().view(dtype=np.dtype([('a', 'u1'), ('b', 'u1')]))
array([(1, 2), (3, 4)], dtype=[('a', 'u1'), ('b', 'u1')])
在这种简单的情况下,这很好,但是如果您选择使用 View ,有时您必须担心数组是如何打包的。请注意, View 不会复制底层缓冲区!如果您使用大型阵列,这可以使其效率更高。

关于python - 将numpy数组转换为结构化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64051498/

相关文章:

javascript - 如何以字符串形式返回所有输入的新数组?

javascript - 按重复模式打印数组值

python - Matplotlib 中公共(public) x 轴上的多个图具有公共(public) y 轴标签

python - 在 Emacs 中使用 ropemacs 自动补全 python.el

python - 如何在 urllib2.URLError 上打印响应正文?

c++ - 概率计算器中的段错误

python - 尝试将 pyx 文件导入 Jupyter 时出现“ImportError : No module named . ..”

python-3.x - 抓取时绕过 403

python - 如何在 tkinter text =""属性中包含变量名称?

python - 如何解决 int 太长而无法转换为 float 错误?