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

如何将元素为元组的object类型NumPy数组转换为int类型数组?

解决object类型元组数组转int数组的问题

你遇到的报错是因为原数组是dtype=object,每个元素是独立的元组,直接用np.array(..., dtype=int)时,NumPy无法将元组直接映射为int类型的数组元素。下面是两种可行的解决方法:

方法1:使用np.vstack拼接元组

np.vstack可以将object数组中的每个元组作为一行,拼接成二维数组,之后再指定类型:

import numpy as np

array_of_tuples = np.zeros(2, dtype=object)
array_of_tuples[0] = 1,2
array_of_tuples[1] = 2,3

result = np.vstack(array_of_tuples).astype(int)
print(result)
# 输出:
# [[1 2]
#  [2 3]]

方法2:通过列表推导式中转

先遍历object数组提取每个元组,组成新的序列后再转成int数组:

result = np.array([item for item in array_of_tuples], dtype=int)
# 或者显式转成列表/元组
result = np.array([tuple(item) for item in array_of_tuples], dtype=int)

这两种方法都能将原数组转换为shape=(2,2)的int类型数组,解决报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:35:13