【问题标题】:Remove rows with missing values denoted by '?'删除带有“?”表示的缺失值的行
【发布时间】:2017-04-03 00:22:00
【问题描述】:

我有一个 .csv 文件,其中包含缺少值的行。这些值而不是null,由字符? 表示。

如果df.na.drop() 不起作用(因为缺少的值不是null),我如何删除至少包含一列值为? 的行?

数据如下所示(我有 35 列 - 可以在任何这些列中找到缺失值)

+-------+--------+------+-------+
| col_1 | col_2  |  ... | col_35|
+-------+--------+------+-------+
| 0.75  |   ?    |  ... |   15  |
|   ?   | Helen  |  ... |   21  |
| -1.2  | George |  ... |    ?  |
|   ?   | Andrew |  ... |   129 |
| 0.12  | Maria  |  ... |   12  |   // Should not be deleted
+-------+--------+------+-------+

这是读取文件的代码。

val df = sparkSession.read
    .format("com.databricks.spark.csv")
    .option("header", "true")
    .option("mode", "DROPMALFORMED")
    .load("data.csv")
    .toDF()

【问题讨论】:

    标签: scala apache-spark missing-data


    【解决方案1】:

    如果? 表示缺失值,您只需配置阅读器即可识别:

    val df = spark.read
      .format("csv")
      .option("nullValue", "?")  // Use "?" as null character
      .option("header", "true")
      .option("mode", "DROPMALFORMED")
      .load("data.csv")
      .toDF()
    

    并使用标准na.drop:

    df.na.drop
    

    【讨论】:

      【解决方案2】:

      您可以使用 spark 数据帧中的 UDF 将 ? 转换为 null 值。

      示例代码如下:

      import org.apache.spark.sql.functions.udf
      
      val df = sc.parallelize(
        Seq(("a", "B", "c"), ("D", "e", "?"), ("G", "?", "I"))).toDF("x", "y", "z")
      // Function returns the input itself or null if it is a '?'
      def replace: (String => String) = { value => if (value == "?") null else value }
      // We create a UDF of that function because we want to run this on the entire column
      val replaceudf = udf(replace)
      Apply the method to all columns of the data frame
      df.select(df.columns.map(c => replaceudf(col(c)).alias(c)): _*)
      
      df.show
      /* Output
      +---+----+----+
      |  x|   y|   z|
      +---+----+----+
      |  a|   B|   c|
      |  D|   e|null|
      |  G|null|   I|
      +---+----+----+
      */
      

      现在您可以对数据框应用所有 NA 操作。我希望这会有所帮助。

      【讨论】:

      • 您可以在此处跳过 UDF:df.columns.map(c => when(coalesce(col(c) =!= "?", lit(false)), col(c))).
      猜你喜欢
      • 2020-05-09
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2013-08-16
      • 1970-01-01
      • 2018-10-02
      相关资源
      最近更新 更多