PySpark:利用映射DataFrame批量替换多列值(避免多次左连接)
问题描述
需要使用映射DataFrame(df2 VOTE MAPPING)替换目标DataFrame(df1 EXAM)中多列的值,由于实际列数远多于示例中的列数,希望避免执行多次左连接操作。
示例数据
df1 EXAM
| id | question1 | question2 | question3 |
|---|---|---|---|
| 1 | 12 | 12 | 5 |
| 2 | 12 | 13 | 6 |
| 3 | 3 | 7 | 5 |
df2 VOTE MAPPING
| id | description |
|---|---|
| 3 | bad |
| 5 | insufficient |
| 6 | sufficient |
| 12 | very good |
| 13 | excellent |
期望输出
| id | question1 | question2 | question3 |
|---|---|---|---|
| 1 | very good | very good | insufficient |
| 2 | very good | excellent | sufficient |
| 3 | bad | null | insufficient |
Edit 1: 修正了投票映射中excellent对应的id值
解决方案
不用多次左连接,直接把映射表转成字典,批量替换目标列就行:
- 从
df2生成映射字典:
mapping_dict = df2.set_index('id')['description'].to_dict()
- 选中需要替换的列(排除
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
相关产品推荐
相关产品推荐

