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

PySpark:利用映射DataFrame批量替换多列值(避免多次左连接)

问题描述

需要使用映射DataFrame(df2 VOTE MAPPING)替换目标DataFrame(df1 EXAM)中多列的值,由于实际列数远多于示例中的列数,希望避免执行多次左连接操作。

示例数据

df1 EXAM

idquestion1question2question3
112125
212136
3375

df2 VOTE MAPPING

iddescription
3bad
5insufficient
6sufficient
12very good
13excellent

期望输出

idquestion1question2question3
1very goodvery goodinsufficient
2very goodexcellentsufficient
3badnullinsufficient

Edit 1: 修正了投票映射中excellent对应的id值

解决方案

不用多次左连接,直接把映射表转成字典,批量替换目标列就行:

  1. 从df2生成映射字典:
mapping_dict = df2.set_index('id')['description'].to_dict()
  1. 选中需要替换的列(排除id列),一次性替换所有列:
cols_to_replace = df1.columns.drop('id')
df1[cols_to_replace] = df1[cols_to_replace].replace(mapping_dict)

如果希望把不在映射里的值转为null(对应输出的null),改用applymap配合字典的get方法:

df1[cols_to_replace] = df1[cols_to_replace].applymap(lambda x: mapping_dict.get(x, None))

这样就能一次处理所有需要替换的列,效率远高于多次左连接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 10:50:37