Pyspark:通过搜索字典替换列中的值

新手上路,请多包涵

我是 PySpark 的新手。

我有一个 Spark DataFrame df 有一列“device_type”。

我想将“平板电脑”或“电话”中的每个值替换为“电话”,并将“PC”替换为“桌面”。

在 Python 中,我可以执行以下操作,

 deviceDict = {'Tablet':'Mobile','Phone':'Mobile','PC':'Desktop'}
df['device_type'] = df['device_type'].replace(deviceDict,inplace=False)

如何使用 PySpark 实现此目的?谢谢!

原文由 Yuehan Lyu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

您可以使用 na.replace

 df = spark.createDataFrame([
    ('Tablet', ), ('Phone', ),  ('PC', ), ('Other', ), (None, )
], ["device_type"])

df.na.replace(deviceDict, 1).show()

 +-----------+
|device_type|
+-----------+
|     Mobile|
|     Mobile|
|    Desktop|
|      Other|
|       null|
+-----------+

或地图文字:

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

mapping = create_map([lit(x) for x in chain(*deviceDict.items())])

df.select(mapping[df['device_type']].alias('device_type'))

 +-----------+
|device_type|
+-----------+
|     Mobile|
|     Mobile|
|    Desktop|
|       null|
|       null|
+-----------+

请注意,后一种解决方案会将映射中不存在的值转换为 NULL 。如果这不是您想要的行为,您可以添加 coalesce

 from pyspark.sql.functions import coalesce

df.select(
    coalesce(mapping[df['device_type']], df['device_type']).alias('device_type')
)

 +-----------+
|device_type|
+-----------+
|     Mobile|
|     Mobile|
|    Desktop|
|      Other|
|       null|
+-----------+

原文由 zero323 发布,翻译遵循 CC BY-SA 3.0 许可协议

经过大量搜索和替代方案后,我认为使用 python 字典替换的最简单方法是使用 pyspark 数据框方法 replace

 deviceDict = {'Tablet':'Mobile','Phone':'Mobile','PC':'Desktop'}
df_replace = df.replace(deviceDict,subset=['device_type'])

这将用字典替换所有值,如果您传递字典参数和子集参数,则可以使用 df.na.replace() 获得相同的结果。他的 文档 不够清楚,因为如果您搜索函数 replace 您将得到两个参考,一个在 pyspark.sql.DataFrame.replace 中,另一个在 pyspark.sql.DataFrameNaFunctions.replace 的一侧,但是两个参考使用的示例代码 df.na.replace 所以不清楚你是否可以实际使用 df.replace

原文由 José 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题