首页 > 解决方案 > 如何在pyspark中添加一个指示每行nan值数量的附加列

问题描述

我想计算每列(包含整数值)的 nan 值的数量,并添加指示这些 nan 值的附加列。

我们以一个简单的 df 为例。

标签: pyspark

解决方案


让我们假设您的数据框是df并且您想要扫描它的所有现有列。

from functools import reduce
from operator import add

columns2scan = df.columns ## change this if you only want part of columns to scan
df.withColumn('num_nulls', (reduce(add,(F.when(F.col(x).isNull(),1).otherwise(0) for x in columns2scan )))).show()

例子:

df.show()  
+----+----+----+
|col1|col2|col3|
+----+----+----+
|null|   y|   y|
|null|   x|null|
|   x|null|null|
|null|null|null|
+----+----+----+

然后使用上面的代码我们得到:

+----+----+----+---------+
|col1|col2|col3|num_nulls|
+----+----+----+---------+
|null|   y|   y|        1|
|null|   x|null|        2|
|   x|null|null|        2|
|null|null|null|        3|
+----+----+----+---------+

推荐阅读