【问题标题】:Read CSV to a Dataframe with less header and more values in a record将 CSV 读取到记录中具有更少标题和更多值的数据帧
【发布时间】:2022-01-27 13:20:30
【问题描述】:

如何在 Spark 中读取结构如下的 csv 文件:

id,name,address
1,"ashu","building","street","area","city","state","pin"

使用阅读器时:

val df = spark.read.option("header",true).csv("input/input1.csv")

我正在记录直到 CSV 中的第三个值。

+---+----+--------+
| id|name| address|
+---+----+--------+
|  1|ashu|building|
+---+----+--------+

如何让 Spark 读取单个数据框列 address 中从第三个值到最后一个值的所有值,例如:

+---+----+-----------------------------------------------+
| id|name| address                                       |
+---+----+-----------------------------------------------+
|  1|ashu|"building","street","area","city","state","pin"|
+---+----+-----------------------------------------------+

【问题讨论】:

    标签: dataframe scala csv apache-spark apache-spark-sql


    【解决方案1】:

    我的答案符合您使用 CSV 的要求。这是做你想做的最不痛苦的方式。

    修改您的 CSV 文件,使其使用“|”拆分字段而不是“,”。这将允许您在列中包含“,”。

    id,name,address
    1|"ashu"|"building","street","area","city","state","pin"
    

    修改你的代码:

    val df = spark.read
          .option("header",true)
          .option("delimiter", '|')
          .csv("input/input1.csv")
    

    【讨论】:

      【解决方案2】:

      如果您可以修复您的输入文件以使用另一个分隔符,那么您应该这样做。

      但是,如果您没有这种可能性,您仍然可以读取没有标题的文件并指定自定义架构。然后,连接 6 个address 列以获得所需的数据帧:

      import org.apache.spark.sql.types._
      
      val schema = StructType(
        Array(
          StructField("id", IntegerType, true),
          StructField("name", StringType, true),
          StructField("address1", StringType, true),
          StructField("address2", StringType, true),
          StructField("address3", StringType, true),
          StructField("address4", StringType, true),
          StructField("address5", StringType, true),
          StructField("address6", StringType, true)
        )
      )
      
      val input = spark.read.schema(schema).csv("input/input1.csv")
      
      val df = input.filter("name != 'name'").withColumn(
        "address",
        concat_ws(", ", (1 to 6).map(n => col(s"address$n")):_*)
      ).select("id", "name", "address")
      
      df.show(false)
      
      //+---+----+----------------------------------------+
      //|id |name|address                                 |
      //+---+----+----------------------------------------+
      //|1  |ashu|building, street, area, city, state, pin|
      //+---+----+----------------------------------------+
      

      【讨论】:

        猜你喜欢
        • 2017-03-22
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 2020-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多