gpt4 book ai didi

scala - 在文本文件中写入/存储数据帧

转载 作者:行者123 更新时间:2023-12-04 17:53:28 29 4
gpt4 key购买 nike

我正在尝试写 dataframetext文件。如果文件包含单列,那么我可以在文本文件中写入。如果文件包含多列,那么我将面临一些错误

Text data source supports only a single column, and you have 2 columns.


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他们与 empty字符为
val op= sourcefile.rdd.map(_.toString().replace("[","").replace("]", "")).saveAsTextFile("C:/Users/phadpa01/Desktop/op")

甚至可以使用 regex

关于scala - 在文本文件中写入/存储数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44537889/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com