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

如何移除字母字符并将DataFrame的object类型id列转为integer类型?

解决方案

你可以通过正则表达式移除所有非数字字符,再将结果转换为整数类型,具体操作如下:

  1. 清理非数字内容:用str.replace()配合正则\D(匹配任意非数字字符),把id列里的字母、横线等非数字内容清空。
  2. 转换数据类型:将处理后的字符串列用astype(int)转为整数类型。

完整代码示例

import pandas as pd

data = {'id':['9011001', '9011001-83V', '9011001-78G', '9011001-56V'],
        'av':[0, 1, 0, 1]}
 
df = pd.DataFrame(data)

# 移除所有非数字字符
df['id'] = df['id'].str.replace(r'\D', '', regex=True)
# 转换为整数类型
df['id'] = df['id'].astype(int)

# 验证结果
print(df.dtypes)
print(df)

输出结果

id     int64
av     int64
dtype: object
        id  av
0  9011001   0
1  901100183   1
2  901100178   0
3  901100156   1

补充说明

如果数据中存在处理后为空的字符串(比如原id全是非数字),可以用pd.to_numeric()设置errors='coerce'将无效值转为NaN,再用支持空值的整数类型存储:

df['id'] = pd.to_numeric(df['id'].str.replace(r'\D', '', regex=True), errors='coerce').astype('Int64')

内容的提问来源于stack exchange,提问作者Anas.S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:20:44