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
相关产品推荐
相关产品推荐

