从scala中的Dataframe中删除不需要的列

5f0d552i  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(585)

我对scala还很陌生,有一种情况,我有一个包含多列的Dataframe,其中一些列在随机的地方有随机的空值。我需要找到任何这样的列甚至有一个空值,并将其从Dataframe中删除。


#### Input

| Column 1      | Column 2      | Column 3      | Column 4      | Column 5      |
| --------------| --------------| --------------| --------------| --------------|
|(123)-456-7890 | 123-456-7890  |(123)-456-789  |               |(123)-456-7890 |
|(123)-456-7890 | 123-4567890   |(123)-456-7890 |(123)-456-7890 | null          |
|(123)-456-7890 | 1234567890    |(123)-456-7890 |(123)-456-7890 | null          |

#### Output

| Column 1      | Column 2      |
| --------------| --------------| 
|(123)-456-7890 | 123-456-7890  |
|(123)-456-7890 | 123-4567890   |
|(123)-456-7890 | 1234567890    |

请告知。谢谢您。

aamkag61

aamkag611#

我建议分两步进行:
排除不是 nullable 从Dataframe
组合至少包含 null 把它们一起扔掉
创建混合使用可空/不可空列的示例Dataframe:

import org.apache.spark.sql.Column
import org.apache.spark.sql.types._

val df0 = Seq(
  (Some(1), Some("x"), Some("a"), None),
  (Some(2), Some("y"), None,      Some(20.0)),
  (Some(3), Some("z"), None,      Some(30.0))
).toDF("c1", "c2", "c3", "c4")

val newSchema = StructType(df0.schema.map{ field =>
    if (field.name == "c1") field.copy(name = "c1_notnull", nullable = false) else field
  })

// Revised dataframe with non-nullable `c1`
val df = spark.createDataFrame(df0.rdd, newSchema)

执行步骤1和2:

val nullableCols = df.schema.collect{ case StructField(name, _, true, _) => name }
// nullableCols: Seq[String] = List(c2, c3, c4)

val colsWithNulls = nullableCols.filter(c => df.where(col(c).isNull).count > 0)
// colsWithNulls: Seq[String] = List(c3, c4)

df.drop(colsWithNulls: _*).show
// +----------+---+
// |c1_notnull| c2|
// +----------+---+
// |         1|  x|
// |         2|  y|
// |         3|  z|
// +----------+---+

相关问题