如何将生成的 RDD 写入 Spark python 中的 csv 文件 [英] How to write the resulting RDD to a csv file in Spark python
问题描述
我有一个结果 RDD labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)
.这具有以下格式的输出:
I have a resulting RDD labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)
. This has output in this format:
[(0.0, 0.08482142857142858), (0.0, 0.11442786069651742),.....]
我想要的是创建一个 CSV 文件,其中一列用于 labels
(上面输出中元组的第一部分)和一列用于 predictions
(第二部分元组输出).但我不知道如何使用 Python 在 Spark 中写入 CSV 文件.
What I want is to create a CSV file with one column for labels
(the first part of the tuple in above output) and one for predictions
(second part of tuple output). But I don't know how to write to a CSV file in Spark using Python.
如何使用上述输出创建 CSV 文件?
How can I create a CSV file with the above output?
推荐答案
只需 map
RDD 的行(labelsAndPredictions
)到字符串(CSV 的行)然后使用 rdd.saveAsTextFile()
.
Just map
the lines of the RDD (labelsAndPredictions
) into strings (the lines of the CSV) then use rdd.saveAsTextFile()
.
def toCSVLine(data):
return ','.join(str(d) for d in data)
lines = labelsAndPredictions.map(toCSVLine)
lines.saveAsTextFile('hdfs://my-node:9000/tmp/labels-and-predictions.csv')
这篇关于如何将生成的 RDD 写入 Spark python 中的 csv 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!