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),.....]
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.
How can I create a CSV file with the above output?
It's not good to just join by commas because if fields contain commas, they won't be properly quoted, e.g.
','.join(['a', 'b', '1,2,3', 'c'])
gives youa,b,1,2,3,c
when you'd wanta,b,"1,2,3",c
. Instead, you should use Python's csv module to convert each list in the RDD to a properly-formatted csv string:Since the csv module only writes to file objects, we have to create an empty "file" with
io.StringIO("")
and tell the csv.writer to write the csv-formatted string into it. Then, we useoutput.getvalue()
to get the string we just wrote to the "file". To make this code work with Python 2, just replace io with the StringIO module.If you're using the Spark DataFrames API, you can also look into the DataBricks save function, which has a csv format.
Just
map
the lines of the RDD (labelsAndPredictions
) into strings (the lines of the CSV) then userdd.saveAsTextFile()
.I know this is an old post. But to help someone searching for the same, here's how I write a two column RDD to a single CSV file in PySpark 1.6.2
The RDD:
Now the code:
The DF:
Now write to CSV
P.S: I am just a beginner learning from posts here in Stackoverflow. So I don't know whether this is the best way. But it worked for me and I hope it will help someone!