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

如何将pandas DataFrame列中列表元素按字典映射替换为对应值

报错原因

map()方法传入字典时,会把列中每个单元格的整体值作为字典的键查询对应值,而你的单元格值是列表,列表属于不可哈希类型,无法作为字典的键,因此触发该错误。你的需求是替换列表内部的每个字符串元素,而非替换列表本身,因此不能直接把字典传给map()。

解决方案

方法1:apply + 列表推导式(小数据量首选,代码简洁易读)

对每个单元格的列表做遍历,逐个元素查询映射字典:

# 替换为你的实际列名和映射字典名
df["your_column"] = df["your_column"].apply(lambda x: [mapping_dict[item] for item in x])

如果存在列表元素不在映射字典的情况,可添加兜底值避免抛出KeyError:

# 示例兜底值为-1,可根据需求调整
df["your_column"] = df["your_column"].apply(lambda x: [mapping_dict.get(item, -1) for item in x])

方法2:explode + map + 聚合(大数据量首选,性能更优)

先把列表拆分为单行单个元素,用向量化的map()做映射,再按原索引聚合回列表:

df["your_column"] = df["your_column"].explode().map(mapping_dict).groupby(level=0).agg(list)

测试示例

可运行以下代码验证效果:

import pandas as pd

# 构造测试数据
df = pd.DataFrame({
    "your_column": [["a", "b"], ["c", "a", "d"], ["b"]]
})
mapping_dict = {"a": 1, "b": 2, "c": 3, "d": 4}

# 执行替换
df["your_column"] = df["your_column"].apply(lambda x: [mapping_dict[item] for item in x])
print(df)

输出结果:

your_column
0        [1, 2]
1     [3, 1, 4]
2           [2]

内容的提问来源于stack exchange,提问作者Matthew D'vertola

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:45:00