You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将元组组成的一维numpy数组转换为二维numpy数组?

解决结构化numpy数组转二维数组的问题

你可以用以下几种高效方法完成转换:

方法1:利用view和reshape(性能最优)

由于你的结构化数组每个元素都是两个<i4(32位整数)类型,直接通过view读取底层连续数据,再重塑形状即可:

import numpy as np
the_tuples = np.array([(1, 4), (7, 8)], dtype=[('f0', '<i4'), ('f1', '<i4')])
the_2Darray = the_tuples.view('<i4').reshape(-1, 2)

方法2:字段堆叠法

提取每个字段的一维数组,再沿列方向堆叠成二维数组:

import numpy as np
the_tuples = np.array([(1, 4), (7, 8)], dtype=[('f0', '<i4'), ('f1', '<i4')])
the_2Darray = np.stack([the_tuples['f0'], the_tuples['f1']], axis=1)

方法3:你的原始方法(可行但规模数据下效率较低)

你尝试的解包转换是有效的,只是处理大规模数据时,性能不如前两种numpy原生方法:

import numpy as np
the_tuples = np.array([(1, 4), (7, 8)], dtype=[('f0', '<i4'), ('f1', '<i4')])
the_2Darray = np.array([*the_tuples])

三种方法最终都会得到目标二维数组:

array([[1, 4],
       [7, 8]])

内容的提问来源于stack exchange,提问作者geekygeek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 12:10:16