处理 pyspark 数据框中的空值

Handling null value in pyspark dataframe

我有 pyspark dataframe 一些数据,我想 substring 列的一些数据,该列也包含一些 null 值。 这是我的数据框

+-------------+
|          Name|
+--------------+
| Asia201909284|
|    US20190928|
|Europ201909287|
|          null|
|     something|
|       nothing|
+--------------+

我想从第 Name

列中删除 Asia, US, Europ

这是我已经尝试过的代码。

fun_asia = udf(lambda x: x[4:len(x)])
fun_us = udf(lambda x: x[2:len(x)])
fun_europ = udf(lambda x: x[5:len(x)])
df1.withColumn("replace", \
               when(df1.Name.isNull(),df1.Name)\
               .when(df1.Name.like("Asia%"),fun_asia(col('Name')))\
               .when(df1.Name.like("US%"),fun_us(col('Name')))\
               .when(df1.Name.like("Europ%"),fun_europ(col('Name')))
               .otherwise(df1.Name)
              ).show()

如果该列中没有 null 值,它可以正常工作。但如果有一些 null 值,它会给出一个错误,如 len() 无法计算空值。

错误按摩

TypeError: object of type 'NoneType' has no len()

让我感到困惑的是,为什么它的调用也很有趣 null 值。 以及如何克服我的问题并获得我想要的结果,感谢任何帮助。

我想要的实际结果

+--------------+---------+
|          Name|  replace|
+--------------+---------+
| Asia201909284|201909284|
|    US20190928| 20190928|
|Europ201909287|201909287|
|          null|     null|
|     something|something|
|       nothing|  nothing|
+--------------+---------+

一种方法是使用 whenisNull() 条件来处理 when column is null 条件:

df1.withColumn("replace", \
               when(df1.Name.like("Asia%"),fun_asia(col('Name')))\
               .when(df1.Name.like("US%"),fun_us(col('Name')))\
               .when(df1.Name.like("Europ%"),fun_europ(col('Name')))
               .when(df1.Name.isNull(), df1.Name)
               .otherwise(df1.Name)
              ).show()

编辑2:

您可以更改您的 udf 以处理空值:

fun_asia = udf(lambda x: x[4:len(x)] if x else None)
fun_us = udf(lambda x: x[2:len(x)] if x else None)
fun_europ = udf(lambda x: x[5:len(x)] if x else None)
df1.withColumn("replace", \
               when(df1.Name.isNull(),df1.Name)\
               .when(df1.Name.like("Asia%"),fun_asia(col('Name')))\
               .when(df1.Name.like("US%"),fun_us(col('Name')))\
               .when(df1.Name.like("Europ%"),fun_europ(col('Name')))
               .otherwise(df1.Name)
              ).show()
+--------------+---------+
|          Name|  replace|
+--------------+---------+
| Asia201909284|201909284|
|    US20190928| 20190928|
|Europ201909287|201909287|
|          null|     null|
|     something|something|
|       nothing|  nothing|
+--------------+---------+