火花CSV到数据帧跳过第一行
问题描述:
我使用CSV加载到数据帧 -火花CSV到数据帧跳过第一行
sqlContext.read.format("com.databricks.spark.csv").option("header", "true").
option("delimiter", ",").load("file.csv")
但我输入文件中包含的第一行和头从第二行中的日期。 例子 -
20160612
id,name,age
1,abc,12
2,bcd,33
我怎么可以跳过此第一排,同时将CSV到数据帧?
答
这里是我能想到的,因为数据砖模块似乎并没有提供一个跳过行选项的几个选项:
选择一个:在第一行的前面加上“#”字符,并且该行将被自动视为注释并被data.bricks csv模块忽略;
选择二:创建自定义模式,并指定mode
选项为DROPMALFORMED
,因为它含有较少的令牌在customSchema于预期,这将下降的第一行:
import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType};
val customSchema = StructType(Array(StructField("id", IntegerType, true),
StructField("name", StringType, true),
StructField("age", IntegerType, true)))
val df = sqlContext.read.format("com.databricks.spark.csv").
option("header", "true").
option("mode", "DROPMALFORMED").
schema(customSchema).load("test.txt")
df.show
16/06/12 21:24:05 WARN CsvRelation $:数字格式异常。删除 畸形行:ID,姓名,年龄
+---+----+---+
| id|name|age|
+---+----+---+
| 1| abc| 12|
| 2| bcd| 33|
+---+----+---+
注意这里的警告消息,它说下跌畸形行:
选择三:写自己的解析器来丢弃没有按”行t长度为三:
val file = sc.textFile("pathToYourCsvFile")
val df = file.map(line => line.split(",")).
filter(lines => lines.length == 3 && lines(0)!= "id").
map(row => (row(0), row(1), row(2))).
toDF("id", "name", "age")
df.show
+---+----+---+
| id|name|age|
+---+----+---+
| 1| abc| 12|
| 2| bcd| 33|
+---+----+---+