读取 CSV 文件时是否可以选择从第 2 行或以下开始?

When reading a CSV is there an option to start on row 2 or below?

我正在使用下面的示例代码将一堆 CSV 文件读取到数据框中。

val df = spark.read.format("csv")
   .option("sep","|")
   .option("inferSchema","true")
   .option("header","false")
   .load("mnt/rawdata/corp/ABC*.gz")

我希望有一种方法可以从第 2 行或以下开始,因为第 1 行包含有关这些文件的一些基本元数据,并且第一行有 4 个竖线字符,所以 Spark 认为该文件有 4 列,但它实际上在实际数据中有超过 100 列。

我试过使用 inferSchema 和 header 但我什么也做不了。

如果 CSV 中的第一行与实际的列数和名称不匹配,您可能需要手动定义架构,然后尝试以下组合:

val df = spark.read.format("csv")
   .option("sep","|")
   .option("inferSchema","false")
   .option("header","true")     
   .schema(mySchema)
   .option("enforceSchema","true")
   .load(...

Full list of CSV options

请注意,对于 Spark 2.3 及更高版本,您可以使用 shorthand、SQL-style 符号来定义模式——简单字符串 "column1 type1, column2 type2, ..."

但是,如果您的 header 不止一行,您可能会被迫使用附加选项 .option("mode","DROPMALFORMED") 忽略所有 "errors"。

你说得对!您需要定义一个自定义模式!我最终选择了这个。

import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType};
import org.apache.spark.sql.functions.input_file_name

val customSchema = StructType(Array(
    StructField("field1", StringType, true),
    StructField("field2", StringType, true),
    StructField("field3", StringType, true),
    StructField("field4", StringType, true),
    StructField("field5", StringType, true),
    StructField("field6", StringType, true),
    StructField("field7", StringType, true)))

val df = sqlContext.read
    .format("com.databricks.spark.csv")
    .option("header", "false")
    .option("sep", "|")
    .schema(customSchema)
    .load("mnt/rawdata/corp/ABC*.gz")
    .withColumn("file_name", input_file_name())