[英]python/pyspark - Reading special characters from csv and writing it back to the file
[英]writing a csv with column names and reading a csv file which is being generated from a sparksql dataframe in Pyspark
我已經用 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 或記事本++打開???
試試
df.coalesce(1).write.format('com.databricks.spark.csv').save('path+my.csv',header = 'true')
請注意,這可能不是您當前設置的問題,但在極大的數據集上,您可能會遇到驅動程序的內存問題。 這也將需要更長的時間(在集群場景中),因為一切都必須推回到一個位置。
以防萬一,在 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")
使用 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)
以下應該可以解決問題:
df \
.write \
.mode('overwrite') \
.option('header', 'true') \
.csv('output.csv')
或者,如果您希望結果在單個分區中,您可以使用coalesce(1)
:
df \
.coalesce(1) \
.write \
.mode('overwrite') \
.option('header', 'true') \
.csv('output.csv')
但是請注意,這是一項昂貴的操作,對於超大數據集可能不可行。
得到了第一個問題的答案,這是將一個額外的參數 header = 'true' 與 csv 語句一起傳遞的問題
df.write.format('com.databricks.spark.csv').save('path+my.csv',header = 'true')
#第二個問題的替代方案
使用 topandas.to_csv ,但我又不想在這里使用熊貓,所以請建議是否有其他方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.