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

Pandas如何根据ID映射字典替换值并为每个新值复制对应行

解决方案

最简洁的符合Python风格的实现只需要两行核心代码,依赖pandas原生的map+explode方法(pandas 0.25及以上版本支持):

# 将原ID替换为映射后的列表
df['ID'] = df['ID'].map(id_mapping)
# 展开列表为单独行,直接生成连续新索引得到目标结果
new_df = df.explode('ID', ignore_index=True)

代码说明

  1. Series.map()方法会按照你提供的id_mapping字典,把每个原ID值替换为对应的新ID列表,此时ID列的每一行都是列表类型
  2. DataFrame.explode()方法会将指定列的列表元素逐行拆分,其他列的数值会自动对应复制,参数ignore_index=True可以直接生成从0开始的连续新索引,不需要额外调用reset_index
  3. 最终输出的new_df和你期望的结构完全一致。

如果使用的是不支持explode的旧版本pandas,也可以用下面的兼容写法:

new_df = df.loc[df.index.repeat(df['ID'].map(id_mapping).str.len())].copy()
new_df['ID'] = [i for ids in df['ID'].map(id_mapping) for i in ids]
new_df = new_df.reset_index(drop=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:51:03