gpt4 book ai didi

pyspark - 在 Spark 中,如果数据框中没有行,如何在文件中写入 header ?

转载 作者:行者123 更新时间:2023-12-04 17:35:14 26 4
gpt4 key购买 nike

如果数据框中没有行,我想在文件中写入标题,目前当我将空数据框写入文件时,会创建文件,但其中没有标题。

我正在使用这些设置和命令编写数据框:

Dataframe.repartition(1) \
.write \
.format("com.databricks.spark.csv") \
.option("ignoreLeadingWhiteSpace", False) \
.option("ignoreTrailingWhiteSpace", False) \
.option("header", "true") \
.save('/mnt/Bilal/Dataframe');

我想要文件中的标题行,即使数据框中没有数据行也是如此。

最佳答案

如果你只想拥有头文件。您可以使用 fold left 创建带有空白的每一列并将其保存为您的 csv。我没有使用过 pyspark,但这是在 scala 中完成的方法。大多数代码应该是可重用的,您只需将其转换为 pyspark

val path ="/user/test"
val newdf=df.columns.foldleft(df){(tempdf,cols)=>
tempdf.withColumn(cols, lit(""))}

创建写入头文件的方法

 def createHeaderFile(headerFilePath: String, colNames: Array[String]) {

//format header file path
val fileName = "yourfileName.csv"
val headerFileFullName = "%s/%s".format(headerFilePath, fileName)

val hadoopConfig = new Configuration()
val fileSystem = FileSystem.get(hadoopConfig)
val output = fileSystem.create(new Path(headerFileFullName))
val writer = new PrintWriter(output)

for (h <- colNames) {
writer.write(h + ",")
}
writer.write("\n")
writer.close()
}

在你的DF上调用它

 createHeaderFile(path, newdf.columns)

关于pyspark - 在 Spark 中,如果数据框中没有行,如何在文件中写入 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56946600/

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