我已经用 databrick csv 包启动了 shell
#../spark-1.6.1-bin-hadoop2.6/bin/pyspark --packages com.databricks:spark-csv_2.11:1.3.0
然后我读了一个 csv 文件做了一些 groupby 操作并将它的转储到一个 csv。from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
df = sqlContext.read.format('com.databricks.spark.csv').options(header='true').load(path.csv') ####it has columns and df.columns works fine
type(df) #<class 'pyspark.sql.dataframe.DataFrame'>
#now trying to dump a csv
df.write.format('com.databricks.spark.csv').save('path+my.csv')
#it creates a directory my.csv with 2 partitions
### To create single file i followed below line of code
#df.rdd.map(lambda x: ",".join(map(str, x))).coalesce(1).saveAsTextFile("path+file_satya.csv") ## this creates one partition in directory of csv name
#but in both cases no columns information(How to add column names to that csv file???)
# again i am trying to read that csv by
df_new = sqlContext.read.format("com.databricks.spark.csv").option("header", "true").load("the file i just created.csv")
#i am not getting any columns in that..1st row becomes column names
请不要像在 read_csv 之后或在阅读时提及列名时向数据帧添加架构那样回答。问题 1- 在进行 csv 转储时,有什么方法可以添加列名吗???
问题 2 - 有没有办法创建单个 csv 文件(不是目录),可以由 ms office 或 Notepad++ 打开???
注意:我目前没有使用集群,因为它对于像我这样的 Spark 初学者来说太复杂了。如果有人可以提供有关如何在集群环境中将 to_csv 处理为单个文件的链接,那将是一个很大的帮助。
最佳答案
尝试df.coalesce(1).write.format('com.databricks.spark.csv').save('path+my.csv',header = 'true')
请注意,这可能不是您当前设置的问题,但在极大的数据集上,您可能会遇到驱动程序的内存问题。这也将需要更长的时间(在集群场景中),因为一切都必须推回到一个位置。
关于python - 使用列名编写 csv 并读取从 Pyspark 中的 sparksql 数据框生成的 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38611418/