【问题标题】:While Reading CSV, last column is coming as Null in Spark, Scala在阅读 CSV 时,最后一列在 Spark、Scala 中以 Null 形式出现
【发布时间】:2020-12-31 06:42:25
【问题描述】:

当我尝试使用 Spark 和 scala 读取管道分隔文件时,如下所示:

1|Consumer Goods|101|
2|Marketing|102|

我正在使用命令:

val part = spark.read
    .format("com.databricks.spark.csv")
    .option("delimiter","|")
    .load("file_name")

我得到的结果是:

+---+--------------+---+----+
|_c0|           _c1|_c2| _c3|
+---+--------------+---+----+
|  1|Consumer Goods|101|null|
|  2|     Marketing|102|null|
+---+--------------+---+----+

Spark 正在读取源文件中不存在的最后一列,因为分隔符被称为管道。 有什么替代方法可以让我得到结果:

+---+--------------+---+
|_c0|           _c1|_c2|
+---+--------------+---+
|  1|Consumer Goods|101|
|  2|     Marketing|102|
+---+--------------+---+

【问题讨论】:

  • >>Spark 正在读取源文件中不存在的最后一列 .... 因为您有“|”在每一列的行尾。将其读取为 textFile 并通过管道拆分数据并溢出元组数据,不包括拆分中的最后一个索引值
  • 在创建数据框后删除最后一列。
  • 你的问题解决了吗?

标签: scala dataframe csv apache-spark pyspark


【解决方案1】:

一种解决方案是像这样简单地删除最后一列:

part
  .select(part.columns.dropRight(1).map(col) : _*)
  .show(false)
+---+--------------+---+
|_c0|_c1           |_c2|
+---+--------------+---+
|1  |Consumer Goods|101|
|2  |Marketing     |102|
+---+--------------+---+

另一种解决方案是将文件作为文本文件读取并自行拆分,如下所示:

val text = spark.read.text("file_name")
// Note that the split functions in java/scala/spark ignores a separator that ends
// a string, but that one that starts one
val size = text.head.getAs[String]("value").split("\\|").size

text
  .withColumn("value", split('value, "\\|"))
  .select((0 until size).map(i => 'value getItem i as s"_c$i") : _*)
  .show(false)
+---+--------------+---+
|_c0|_c1           |_c2|
+---+--------------+---+
|1  |Consumer Goods|101|
|2  |Marketing     |102|
+---+--------------+---+

【讨论】:

    【解决方案2】:

    您可以使用以下选项

    df.drop(df.columns(0)) -- for dropping last column in scala
    
    df.drop(df.columns[-1]) -- for dropping last column in pyspark
    

    【讨论】:

      猜你喜欢
      • 2016-09-13
      • 2023-03-26
      • 1970-01-01
      • 2019-05-06
      • 2018-11-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2020-12-13
      相关资源
      最近更新 更多