如何有效地找到 PySpark 数据帧中每列的 Null 和 Nan 值的计数? [英] How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

查看:26
本文介绍了如何有效地找到 PySpark 数据帧中每列的 Null 和 Nan 值的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import numpy as np

data = [
    (1, 1, None), 
    (1, 2, float(5)), 
    (1, 3, np.nan), 
    (1, 4, None), 
    (1, 5, float(10)), 
    (1, 6, float("nan")), 
    (1, 6, float("nan")),
]
df = spark.createDataFrame(data, ("session", "timestamp1", "id2"))

预期输出

每列包含 nan/null 计数的数据框

dataframe with count of nan/null for each column

注意:我在堆栈溢出中发现的先前问题仅检查 null &不是南.这就是为什么我创建了一个新问题.

Note: The previous questions I found in stack overflow only checks for null & not nan. That's why I have created a new question.

我知道我可以在 Spark 中使用 isnull() 函数来查找 Spark 列中 Null 值的数量,但如何在 Spark 数据框中查找 Nan 值?

I know I can use isnull() function in Spark to find number of Null values in Spark column but how to find Nan values in Spark dataframe?

推荐答案

您可以使用此处所示的方法并替换isNullisnan:

You can use method shown here and replace isNull with isnan:

from pyspark.sql.functions import isnan, when, count, col

df.select([count(when(isnan(c), c)).alias(c) for c in df.columns]).show()
+-------+----------+---+
|session|timestamp1|id2|
+-------+----------+---+
|      0|         0|  3|
+-------+----------+---+

df.select([count(when(isnan(c) | col(c).isNull(), c)).alias(c) for c in df.columns]).show()
+-------+----------+---+
|session|timestamp1|id2|
+-------+----------+---+
|      0|         0|  5|
+-------+----------+---+

这篇关于如何有效地找到 PySpark 数据帧中每列的 Null 和 Nan 值的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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