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

将Series中的数字英文单词转换为阿拉伯数字失败求助

解决方法

1. 核心问题:未赋值替换结果

pandas的replace方法默认返回新的Series对象,不会原地修改原数据。你需要将替换后的结果重新赋值给变量:

years_of_exp = years_of_exp.replace(help_dict, regex=True)

2. 优化:确保匹配独立数字单词

如果你的Series元素是包含其他字符的长字符串(比如"two years"),建议给字典的键添加正则单词边界\b,避免误匹配非独立的数字单词(比如"twotwo"中的"two"):

# 生成带单词边界的正则匹配字典
help_dict = {rf'\b{k}\b': v for k, v in help_dict.items()}
# 执行替换并赋值
years_of_exp = years_of_exp.replace(help_dict, regex=True)

完整可运行示例

import pandas as pd

# 模拟你的Series数据
years_of_exp = pd.Series(["two years", "five months", "one week", "zero days"])

help_dict = {
    'one': '1',
    'two': '2',
    'three': '3',
    'four': '4',
    'five': '5',
    'six': '6',
    'seven': '7',
    'eight': '8',
    'nine': '9',
    'zero': '0'
}

# 优化匹配规则
help_dict = {rf'\b{k}\b': v for k, v in help_dict.items()}
# 替换并保存结果
years_of_exp = years_of_exp.replace(help_dict, regex=True)

print(years_of_exp)

运行后输出:

0    2 years
1    5 months
2     1 week
3     0 days
dtype: object

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:45:32