首頁  >  文章  >  後端開發  >  Python讀csv檔案去掉一列後再寫入新的檔案技術教程

Python讀csv檔案去掉一列後再寫入新的檔案技術教程

小云云
小云云原創
2017-12-30 13:23:552329瀏覽

本文主要為大家分享一篇Python讀csv檔案去掉一列後再寫入新的檔案實例,具有很的參考價值,希望對大家有幫助。一起跟隨小編過來看看吧,希望能幫助到大家更好掌握Python

用了兩種.方式解決該問題,都是網上現有的解決方案。

場景說明:

有資料文件,以文字方式儲存,現在有三列user_id,plan_id,mobile_id。目標是得到新檔案只有mobile_id,plan_id。

解決方案

#方案一:#用python的開啟檔案寫檔案的方式直接擼一遍數據,for循環內處理數據並寫入新文件。

#程式碼如下:


def readwrite1( input_file,output_file):
 f = open(input_file, 'r')
 out = open(output_file,'w')
 print (f)
 for line in f.readlines():
 a = line.split(",")
 x=a[0] + "," + a[1]+"\n"
 out.writelines(x)
 f.close()
 out.close()

方案二:用pandas 讀數據到DataFrame 再做資料分割,直接用DataFrame 的寫入功能寫到新檔案

#程式碼如下:


def readwrite2(input_file,output_file): date_1=pd.read_csv(input_file,header=0,sep=',') date_1[['mobile', 'plan_id']].to_csv(output_file, sep=',', header=True,index=False)

從程式碼上看,pandas邏輯更清晰。

下面看下執行的效率吧!


def getRunTimes( fun ,input_file,output_file):
 begin_time=int(round(time.time() * 1000))
 fun(input_file,output_file)
 end_time=int(round(time.time() * 1000))
 print("读写运行时间:",(end_time-begin_time),"ms")

getRunTimes(readwrite1,input_file,output_file) #直接撸数据
getRunTimes(readwrite2,input_file,output_file1) #使用dataframe读写数据

讀取寫入運行時間:976 ms

讀取寫入運行時間:777 ms

input_file 大概27萬的數據,dataframe的效率比for循環效率還是要快一點的,如果數據量更大些,效果是否更明顯呢?

下面試下增加input_file記錄的數量試試,有以下結果

input_file       readwrite1       readwrite2
27W 976 777
55W 1989 1509
110W 4312 3158

#從上面測試結果來看,dataframe的效率提高約30%左右。

相關推薦:

利用python 將目錄下的檔案過濾刪除實例詳解

淺聊Python NLP入門

實例講解python使用者管理系統

以上是Python讀csv檔案去掉一列後再寫入新的檔案技術教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn