【问题标题】:How to return rows with Null values in pyspark dataframe?如何在 pyspark 数据框中返回具有 Null 值的行?
【发布时间】:2019-04-28 10:40:11
【问题描述】:

我正在尝试从 pyspark 数据框中获取具有空值的行。在 pandas 中,我可以在数据帧上使用 isnull() 来实现这一点:

df = df[df.isnull().any(axis=1)]

但在 PySpark 的情况下,当我在命令下方运行时,它会显示 Attributeerror:

df.filter(df.isNull())

AttributeError: 'DataFrame' 对象没有属性 'isNull'。

如何在不检查每一列的情况下获取具有空值的行?

【问题讨论】:

标签: python pyspark apache-spark-sql


【解决方案1】:

您可以使用wherereduce 和列表解析过滤行。例如,给定以下数据框:

df = sc.parallelize([
    (0.4, 0.3),
    (None, 0.11),
    (9.7, None), 
    (None, None)
]).toDF(["A", "B"])

df.show()
+----+----+
|   A|   B|
+----+----+
| 0.4| 0.3|
|null|0.11|
| 9.7|null|
|null|null|
+----+----+

过滤带有一些null 值的行可以通过以下方式实现:

import pyspark.sql.functions as f
from functools import reduce

df.where(reduce(lambda x, y: x | y, (f.col(x).isNull() for x in df.columns))).show()

这给出了:

+----+----+
|   A|   B|
+----+----+
|null|0.11|
| 9.7|null|
|null|null|
+----+----+

在条件语句中,您必须指定 if any (or, |), all (and, &) 等。

【讨论】:

  • 好答案,我想知道如何以编程方式构造布尔表达式
【解决方案2】:

这就是你如何在 scala 中做到这一点

import org.apache.spark.sql.functions._

case class Test(id:Int, weight:Option[Int], age:Int, gender: Option[String])

val df1 = Seq(Test(1, Some(100), 23, Some("Male")), Test(2, None, 25, None), Test(3, None, 33, Some("Female"))).toDF()
    
display(df1.filter(df1.columns.map(c => col(c).isNull).reduce((a,b) => a || b)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多