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

如何将DataFrame中含单个int的list列转换为int类型?

解决方法

根据你的数据情况,分两种场景处理:

场景1:列元素是真正的列表类型

如果predicted列的每个元素确实是仅含单个整数的列表(比如[1]、[0],而非字符串形式的"[1]"),直接提取列表的第一个元素即可:

# 方法1:使用apply提取第一个元素
df_testing['predicted'] = df_testing['predicted'].apply(lambda x: x[0])

# 方法2:使用explode展开(适合单元素列表)
df_testing['predicted'] = df_testing['predicted'].explode().astype(int)

场景2:列元素是字符串类型(看起来像列表)

如果你的数据实际是字符串格式(比如从文件读取时被解析为"[1]"、"[0]"),可以通过以下方式处理:

# 方法1:移除括号后转整数
df_testing['predicted'] = df_testing['predicted'].str.strip('[]').astype(int)

# 方法2:正则提取数字
df_testing['predicted'] = df_testing['predicted'].str.extract(r'(\d+)').astype(int)

你的尝试失败原因分析

第一种尝试失败原因

你使用的df_testing['predicted'].replace('[','',inplace=True)是Series级别的replace,它默认匹配整个元素值而非子串,因此无法替换字符串内部的[和]。需要改用str.replace来操作字符串子串:

# 修正后的第一种方法
df_testing['predicted'] = df_testing['predicted'].astype('str') 
df_testing['predicted'] = df_testing['predicted'].str.replace('[','', regex=False)
df_testing['predicted'] = df_testing['predicted'].str.replace(']','', regex=False)
df_testing['predicted'] = pd.to_numeric(df_testing['predicted'], errors='coerce')

第二种尝试失败原因

你的代码lambda x: list(map(int, x))会将输入的字符串拆分为单个字符(比如"[1]"会被拆成['[', '1', ']']),尝试将[转为整数时自然报错。如果元素是真正的列表,这个代码完全多余;如果是字符串,这种处理逻辑本身就不适用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:55:25