[英]Write/store dataframe in text file
我正在尝试将dataframe
写入text
文件。 如果文件包含单列,那么我可以在文本文件中写入。 如果文件包含多列,那么我将面临一些错误
文本数据源仅支持单列,您有 2 列。
object replace {
def main(args:Array[String]): Unit = {
Logger.getLogger("org").setLevel(Level.ERROR)
val spark = SparkSession.builder.master("local[1]").appName("Decimal Field Validation").getOrCreate()
var sourcefile = spark.read.option("header","true").text("C:/Users/phadpa01/Desktop/inputfiles/decimalvalues.txt")
val rowRDD = sourcefile.rdd.zipWithIndex().map(indexedRow => Row.fromSeq((indexedRow._2.toLong+1) +: indexedRow._1.toSeq)) //adding prgrefnbr
//add column for prgrefnbr in schema
val newstructure = StructType(Array(StructField("PRGREFNBR",LongType)).++(sourcefile.schema.fields))
//create new dataframe containing prgrefnbr
sourcefile = spark.createDataFrame(rowRDD, newstructure)
val op= sourcefile.write.mode("overwrite").format("text").save("C:/Users/phadpa01/Desktop/op")
}
}
您可以将数据帧转换为 rdd 并将行转换为字符串并将最后一行写为
val op= sourcefile.rdd.map(_.toString()).saveAsTextFile("C:/Users/phadpa01/Desktop/op")
已编辑
正如@philantrovert 和@Pravinkumar 指出的那样,上述内容会在输出文件中附加[
和]
,这是真的。 解决方案是replace
它们replace
为empty
字符
val op= sourcefile.rdd.map(_.toString().replace("[","").replace("]", "")).saveAsTextFile("C:/Users/phadpa01/Desktop/op")
甚至可以使用regex
我建议使用csv
或其他分隔格式。 以下是在 Spark 2+ 中以最简洁/优雅的方式写入 .tsv 的示例
val tsvWithHeaderOptions: Map[String, String] = Map(
("delimiter", "\t"), // Uses "\t" delimiter instead of default ","
("header", "true")) // Writes a header record with column names
df.coalesce(1) // Writes to a single file
.write
.mode(SaveMode.Overwrite)
.options(tsvWithHeaderOptions)
.csv("output/path")
您可以另存为文本CSV文件 ( .format("csv")
)
结果将是一个 CSV 格式的文本文件,每列将用逗号分隔。
val op = sourcefile.write.mode("overwrite").format("csv").save("C:/Users/phadpa01/Desktop/op")
更多信息可以在火花编程指南中找到
我认为使用“子字符串”更适合我觉得的所有场景。
请检查以下代码。
sourcefile.rdd
.map(r => { val x = r.toString; x.substring(1, x.length-1)})
.saveAsTextFile("C:/Users/phadpa01/Desktop/op")
我使用 databricks api 将我的 DF 输出保存到文本文件中。
myDF.write.format("com.databricks.spark.csv").option("header", "true").save("output.csv")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.