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

