gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:42:33 32 4
gpt4 key购买 nike

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

原始数据框

<表类="s-表"><头>DataIdObjId名称对象Section_1<正文>我的数据数据名称对象名称rd.111rd.123

Python 字典

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

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

所需的数据框

<表类="s-表"><头>DataIdObjId名称对象Section_1Section_2<正文>我的数据数据名称对象名称rd.111rd.123rd.567

现在我的当前代码出现了这个错误,我真的不知道我做错了什么,因为我不熟悉 pyspark

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

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

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

最佳答案

您可以试试这个(改编自 this answer 添加了 null 处理):

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)

关于python - 从 Pyspark 列中获取值并将其与 Python 字典进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67231153/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com