如何在 PySpark 中用 NULL 替换字符串值? [英] How do I replace a string value with a NULL in PySpark?

查看:64
本文介绍了如何在 PySpark 中用 NULL 替换字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

df.replace('empty-value', None, 'NAME')

基本上,我想用 NULL 替换一些值.但它在这个函数中不接受 None .我该怎么做?

Basically, I want to replace some value with NULL. but it does not accept None in this function. How can I do this?

推荐答案

这会将 name 列中的 empty-value 替换为 None:

This will replace empty-value with None in your name column:

from pyspark.sql.functions import udf
from pyspark.sql.types import StringType


df = sc.parallelize([(1, "empty-value"), (2, "something else")]).toDF(["key", "name"])
new_column_udf = udf(lambda name: None if name == "empty-value" else name, StringType())
new_df = df.withColumn("name", new_column_udf(df.name))
new_df.collect()

输出:

[Row(key=1, name=None), Row(key=2, name=u'something else')]

通过使用旧名称作为 withColumn 中的第一个参数,它实际上将旧的 name 列替换为 UDF 输出生成的新列.

By using the old name as the first parameter in withColumn, it actually replaces the old name column with the new one generated by the UDF output.

这篇关于如何在 PySpark 中用 NULL 替换字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆