如何将元素为元组的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
相关产品推荐
相关产品推荐

