如何替换Pandas DataFrame列表类型列中的所有匹配元素
问题根源
你现在的代码存在两个核心问题:
- 将列表转为字符串后用正则匹配,只要找到第一个匹配项就直接
return,自然只能返回单个替换值 - 本身存储的是整数列表,完全不需要转字符串用正则匹配,直接做整数到字符的映射效率更高、逻辑更清晰
实现代码
最优实现(无需正则)
import pandas as pd # 原始测试数据 data = [["Item_1", [0, 3, 4]], ["Item_2", [22, 4, 5]], ["Item_3", [0, 4, 5]]] df = pd.DataFrame(data, columns=["Item_ID", "Values"]) # 直接用整数作为映射key,不需要正则 replace_dict = { 1: "A", 12: "B", 3: "C", 4: "D", 5: "E", 22: "G", } # 定义替换函数,遍历列表每个元素做匹配 def replace_vals(val_list): res = [] for num in val_list: if num in replace_dict: res.append(replace_dict[num]) return res # 应用函数得到结果 df["corrected_vals"] = df["Values"].apply(replace_vals)
运行后输出和你期望的完全一致:
| Item_ID | Values | corrected_vals |
|---|---|---|
| Item_1 | [0, 3, 4] | ['C', 'D'] |
| Item_2 | [22, 4, 5] | ['G', 'D', 'E'] |
| Item_3 | [0, 4, 5] | ['D', 'E'] |
正则兼容实现(如果你的实际场景必须用正则匹配)
如果你的真实业务规则更复杂,只能用正则实现匹配,可以修改原有函数收集所有匹配结果,而非匹配到第一个就返回:
import re def replace_vals_by_re(x): replace_dict = { r"\b1\b": "A", r"\b12\b": "B", r"\b3\b": "C", r"\b4\b": "D", r"\b5\b": "E", r"\b22\b": "G", } res = [] for pattern, replacer in replace_dict.items(): if re.search(pattern, x, re.IGNORECASE): res.append(replacer) return res # 保留原有转字符串的步骤 df["corrected_vals"] = df["Values"].astype(str).apply(replace_vals_by_re)
内容的提问来源于stack exchange,提问作者user
相关产品推荐
相关产品推荐

