我正在使用 -
将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转换为dataframe时跳过第一行?
答案 0 :(得分:5)
以下是我可以想到的几个选项,因为数据砖模块似乎没有提供跳过线选项:
选项一:添加"#"第一行前面的字符,该行将自动视为注释,并被data.bricks csv模块忽略;
选项二:创建自定义架构并将mode
选项指定为DROPMALFORMED
,这将删除第一行,因为它在customSchema中包含的令牌少于预期:< / p>
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,name,age
+---+----+---+
| id|name|age|
+---+----+---+
| 1| abc| 12|
| 2| bcd| 33|
+---+----+---+
请注意此处的警告消息,其中包含丢弃的格式错误的行:
选项三:编写自己的解析器以删除长度不为3的行:
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|
+---+----+---+