问题
My homework is giving me a hard time with pyspark. I have this view of my "df2" after a groupBy:
df2.groupBy('years').count().show()
+-----+-----+
|years|count|
+-----+-----+
| 2003|11904|
| 2006| 3476|
| 1997| 3979|
| 2004|13362|
| 1996| 3180|
| 1998| 4969|
| 1995| 1995|
| 2001|11532|
| 2005|11389|
| 2000| 7462|
| 1999| 6593|
| 2002|11799|
+-----+-----+
Every attempt to save this (and then load with pandas) to a file gives back the original source data text file form I read with pypspark with its original columns and attributes, only now its .csv but that's not the point. What can I do to overcome this ? For your concern I do not use SparkContext function in the begining of the code, just plain "read" and "groupBy".
回答1:
df2.groupBy('years').count().write.csv("sample.csv")
or
df3=df2.groupBy('years').count()
df3.write.csv("sample.csv")
both of them will create sample.csv
in your working directory
回答2:
You can assign the results into a new dataframe results
, and then write the results to a csv
file. Note that there are two ways to output the csv. If you use spark you need to use .coalesce(1)
to make sure only one file is outputted. The other way is to convert .toPandas()
and use to_csv()
function of pandas DataFrame.
results = df2.groupBy('years').count()
# writes a csv file "part-xxx.csv" inside a folder "results"
results.coalesce(1).write.csv("results", header=True)
# or if you want a csv file, not a csv file inside a folder (default behaviour of spark)
results.toPandas().to_csv("results.csv")
来源:https://stackoverflow.com/questions/65118780/save-a-dataframe-view-after-groupby-using-pyspark