从Pyspark列中获取值,并将其与Python字典进行比较

2024-05-13 08:14:09 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我有一个pyspark数据帧,我想使用Section_1列中的值添加另一列,并在python字典中找到它对应的值。因此,基本上使用节_1单元格中的值作为键,然后在新列中填写python字典中的值,如下所示

原始数据帧

^{tb1}$

Python字典

object_map= {'rd.123' : 'rd.567'}

其中,第1节的值为rd.123,我将在字典中搜索键“rd.123”,并希望返回该值rd.567,并将其放入新列中

所需数据帧

^{tb2}$

现在我在我当前的代码中遇到了这个错误,我不知道我做错了什么,因为我对pyspark不太熟悉

There is an incorrect call to a Column object in your code. Please review your code.

这是我目前正在使用的代码,其中object_map是python字典

test_df = output.withColumn('Section_2', object_map.get(output.Section_1.collect()))

Tags: 数据代码mapoutputyour原始数据字典object
1条回答
网友
1楼 · 发布于 2024-05-13 08:14:09

您可以尝试以下方法(通过添加空处理从this answer改编):

from itertools import chain
from pyspark.sql.functions import create_map, lit, when

object_map = {'rd.123': 'rd.567'}
mapping_expr = create_map([lit(x) for x in chain(*object_map.items())])

df1 = df.filter(df['Section_1'].isNull()).withColumn('Section_2', F.lit(None))

df2 = df.filter(df['Section_1'].isNotNull()).withColumn(
    'Section_2', 
    when(
        df['Section_1'].isNotNull(), 
        mapping_expr[df['Section_1']]
    )
)

result = df1.unionAll(df2)

相关问题 更多 >