有没有办法计算 Spark df 中每行的非空值?

NIT*_*ITS 5 python apache-spark-sql pyspark

我有一个非常宽的 df 和大量的列。我需要在 python 中获取每行非空值的计数。

示例 DF -

+-----+----------+-----+-----+-----+-----+-----+-----+
| name|      date|col01|col02|col03|col04|col05|col06|
+-----+----------+-----+-----+-----+-----+-----+-----+
|name1|2017-12-01|100.0|255.5|333.3| null|125.2|132.7|
|name2|2017-12-01|101.1|105.5| null| null|127.5| null|
Run Code Online (Sandbox Code Playgroud)

我想在 col01-col06 中添加一个包含非空值计数的列 -

+-----+----------+-----+-----+-----+-----+-----+-----+-----+
| name|      date|col01|col02|col03|col04|col05|col06|count|
+-----+----------+-----+-----+-----+-----+-----+-----+-----+
|name1|2017-12-01|100.0|255.5|333.3| null|125.2|132.7|    5| 
|name2|2017-12-01|101.1|105.5| null| null|127.5| null|    3|

Run Code Online (Sandbox Code Playgroud)

我能够像这样在 pandas df 中得到这个 -

df['count']=df.loc[:,'col01':'col06'].notnull().sum(axis=1)     
Run Code Online (Sandbox Code Playgroud)

但到目前为止,spark df 还没有运气:( 有什么想法吗?

gmd*_*mds 7

将值转换nulltrue/ false,然后转换为整数,然后将它们相加:

from pyspark.sql import functions as F
from pyspark.sql.types import IntegerType

df = spark.createDataFrame([[1, None, None, 0], 
                            [2, 3, 4, None], 
                            [None, None, None, None], 
                            [1, 5, 7, 2]], 'a: int, b: int, c: int, d: int')

df.select(sum([F.isnull(df[col]).cast(IntegerType()) for col in df.columns]).alias('null_count')).show()
Run Code Online (Sandbox Code Playgroud)

输出:

+----------+
|null_count|
+----------+
|         2|
|         1|
|         4|
|         0|
+----------+

Run Code Online (Sandbox Code Playgroud)