Pyspark:是否有一种有效的方法来排除仅包含空值但pk的行?

问题描述

我有一个id(PK)和几个列的sdf,后者可能包含空值。 我想找到一种有效的方法来过滤在其列中至少具有一个值的行。

假设这是表格:

+-----------+-------+-------+-------+
|         id| clm_01| clm_02| clm_03|...
+-----------+-------+-------+-------+-
|    10001  |   null|  null |      5|...
|    10002  |      1|     3 |      2|...
|    10003  |   null|  null |   null|...
        ...
+-----------+-------+-------+-------+

从上表中,我想获取ID为10003的行。 使用以下脚本可以轻松完成此操作;

sdf.withColumn(
  'flg',when(
   col('clm_01').isNull() & col('clm_02').isNull() & col('clm_01').isNull(),1).\
  otherwise(0) 
).\
filter(col('flg') != 1)

但是如何将条件子句应用于更多列,而又不重复isNull()链一百次?

谢谢您的帮助。

解决方法

您可以使用coalesceleastgreatest函数。如果所有列均为null,它们将返回null

from pyspark.sql import functions as F

columns = list(set(sdf.columns) - {'id'})
sdf = sdf.filter(F.coalesce(*columns).isNull())

或仅通过coalesce来实现:

sdf = sdf.filter(F.coalesce(*sdf.columns) == F.col('id'))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...