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

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

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

  1. #### Input
  2. | Column 1 | Column 2 | Column 3 | Column 4 | Column 5 |
  3. | --------------| --------------| --------------| --------------| --------------|
  4. |(123)-456-7890 | 123-456-7890 |(123)-456-789 | |(123)-456-7890 |
  5. |(123)-456-7890 | 123-4567890 |(123)-456-7890 |(123)-456-7890 | null |
  6. |(123)-456-7890 | 1234567890 |(123)-456-7890 |(123)-456-7890 | null |
  7. #### Output
  8. | Column 1 | Column 2 |
  9. | --------------| --------------|
  10. |(123)-456-7890 | 123-456-7890 |
  11. |(123)-456-7890 | 123-4567890 |
  12. |(123)-456-7890 | 1234567890 |

请告知。谢谢您。

aamkag61

aamkag611#

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

  1. import org.apache.spark.sql.Column
  2. import org.apache.spark.sql.types._
  3. val df0 = Seq(
  4. (Some(1), Some("x"), Some("a"), None),
  5. (Some(2), Some("y"), None, Some(20.0)),
  6. (Some(3), Some("z"), None, Some(30.0))
  7. ).toDF("c1", "c2", "c3", "c4")
  8. val newSchema = StructType(df0.schema.map{ field =>
  9. if (field.name == "c1") field.copy(name = "c1_notnull", nullable = false) else field
  10. })
  11. // Revised dataframe with non-nullable `c1`
  12. val df = spark.createDataFrame(df0.rdd, newSchema)

执行步骤1和2:

  1. val nullableCols = df.schema.collect{ case StructField(name, _, true, _) => name }
  2. // nullableCols: Seq[String] = List(c2, c3, c4)
  3. val colsWithNulls = nullableCols.filter(c => df.where(col(c).isNull).count > 0)
  4. // colsWithNulls: Seq[String] = List(c3, c4)
  5. df.drop(colsWithNulls: _*).show
  6. // +----------+---+
  7. // |c1_notnull| c2|
  8. // +----------+---+
  9. // | 1| x|
  10. // | 2| y|
  11. // | 3| z|
  12. // +----------+---+
展开查看全部

相关问题