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

Pandas中如何将DataFrame提取的Series字符串列转换为整数

Pandas字符串Series转整数的正确实现方法

报错原因

TypeError: cannot convert the series to <class 'int'> 报错是因为Python内置的int()仅支持转换单个值,无法直接作用于Pandas Series序列对象。

可用转换方案

方案1:astype() 方法(无异常值场景首选)

Pandas内置的astype()可批量对Series所有元素执行类型转换,代码如下:

# 提取子串后直接转整数
variable = df1['Name'].str[11:14].astype(int)

转换后原字符串025、012会被转为整数25、12,可通过print(variable.dtype)验证类型为整型。

方案2:pd.to_numeric() 方法(存在异常值场景首选)

如果提取的子串可能包含非数字内容,可以用该方法灵活处理异常,避免直接中断执行:

import pandas as pd
# errors='coerce' 表示无法转换的值会被置为NaN,也可设置为'ignore'保留原始值
variable = pd.to_numeric(df1['Name'].str[11:14], errors='coerce')

注意事项

  • 如果提取的子串存在前后空白字符,可先调用.str.strip()去除空白后再执行转换,避免报错:
    variable = df1['Name'].str[11:14].str.strip().astype(int)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:36:07