Sat*_*tya 14 apache-spark pyspark pyspark-sql
我用databrick csv包启动了shell
#../spark-1.6.1-bin-hadoop2.6/bin/pyspark --packages com.databricks:spark-csv_2.11:1.3.0
Run Code Online (Sandbox Code Playgroud)
然后我读了一个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
Run Code Online (Sandbox Code Playgroud)
请不要像在read_csv之后或在阅读提及列名时向数据帧添加模式一样回答.
问题1--给csv转储是否有任何方法我可以添加列名称???
问题2 - 是否有一种方法可以创建单个csv文件(不再是目录),可以通过ms office或notepad ++ ???打开
小智 19
尝试
df.coalesce(1).write.format('com.databricks.spark.csv').save('path+my.csv',header = 'true')
请注意,这可能不是您当前设置的问题,但在极大的数据集上,您可能会遇到驱动程序的内存问题.这也将花费更长的时间(在集群场景中),因为一切都必须推回到一个位置.
Fra*_*coM 16
以防万一,在spark 2.1上,您可以使用以下行创建单个csv文件
dataframe.coalesce(1) //So just a single part- file will be created
.write.mode(SaveMode.Overwrite)
.option("mapreduce.fileoutputcommitter.marksuccessfuljobs","false") //Avoid creating of crc files
.option("header","true") //Write the header
.csv("csvFullPath")
Run Code Online (Sandbox Code Playgroud)
有了spark> = 2.o,我们可以做类似的事情
df = spark.read.csv('path+filename.csv', sep = 'ifany',header='true')
df.write.csv('path_filename of csv',header=True) ###yes still in partitions
df.toPandas().to_csv('path_filename of csv',index=False) ###single csv(Pandas Style)
Run Code Online (Sandbox Code Playgroud)
以下应该可以解决问题:
df \
.write \
.mode('overwrite') \
.option('header', 'true') \
.csv('output.csv')
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望结果在单个分区中,您可以使用coalesce(1)
:
df \
.coalesce(1) \
.write \
.mode('overwrite') \
.option('header', 'true') \
.csv('output.csv')
Run Code Online (Sandbox Code Playgroud)
但是请注意,这是一项昂贵的操作,对于超大数据集可能不可行。
归档时间: |
|
查看次数: |
43691 次 |
最近记录: |