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

如何将元素为逗号分隔字符串的Numpy数组转换为整数类型数组

核心报错原因

np.char.split处理单个字符串元素时,返回的是包含字符串列表的数组对象,而非一维字符串数组,直接调用astype(np.int)会尝试将整个列表转换为单个整数,不符合类型转换要求,因此抛出错误。

可行实现方案

方案1:向量化处理(推荐,无需显式循环)

import numpy as np

# 原始数组
myarray = np.array(['31,67,82', '31,72,82', '31,41,77'])

# 全量分割后转列表,再构造整数数组
split_res = np.char.split(myarray, sep=',')
result = np.array(split_res.tolist(), dtype=np.int32)

运行后result就是你期望的二维整数数组格式。

方案2:修改原有循环写法

如果你想沿用原循环逻辑,调整转换规则即可:

a = []
for x in myarray:
    # 先分割为字符串列表,再逐个转整数
    int_items = [int(i) for i in x.split(',')]
    a.append(int_items)
result = np.array(a)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:06:09