轉(zhuǎn)載:https://www.cnblogs.com/crazysquirrel/p/6562320.html?utm_source=tuicool&utm_medium=referral
在數(shù)據(jù)分析中經(jīng)常需要從csv格式的文件中存取數(shù)據(jù)以及將數(shù)據(jù)寫書到csv文件中。將csv文件中的數(shù)據(jù)直接讀取為dict類型和DataFrame是非常方便也很省事的一種做法,以下代碼以鳶尾花數(shù)據(jù)為例。
csv文件讀取為dict
代碼
# -*- coding: utf-8 -*-importcsvwithopen('E:/iris.csv')ascsvfile:? ? reader = csv.DictReader(csvfile, fieldnames=None)# fieldnames默認(rèn)為None,如果所讀csv文件沒有表頭,則需要指定list_1 = [eforeinreader]# 每行數(shù)據(jù)作為一個(gè)dict存入鏈表中csvfile.close()printlist_1[0]
輸出
{'Petal.Length':'1.4','Sepal.Length':'5.1','Petal.Width':'0.2','Sepal.Width':'3.5','Species':'setosa'}
如果讀入的每條數(shù)據(jù)需要單獨(dú)處理且數(shù)據(jù)量較大,推薦逐條處理然后再放入。
list_1 = list()foreinreader:? list_1.append(your_func(e))# your_func為每條數(shù)據(jù)的處理函數(shù)
多條類型為dict的數(shù)據(jù)寫入csv文件
代碼
#? 數(shù)據(jù)data = [{'Petal.Length':'1.4','Sepal.Length':'5.1','Petal.Width':'0.2','Sepal.Width':'3.5','Species':'setosa'},{'Petal.Length':'1.4','Sepal.Length':'4.9','Petal.Width':'0.2','Sepal.Width':'3','Species':'setosa'},{'Petal.Length':'1.3','Sepal.Length':'4.7','Petal.Width':'0.2','Sepal.Width':'3.2','Species':'setosa'},{'Petal.Length':'1.5','Sepal.Length':'4.6','Petal.Width':'0.2','Sepal.Width':'3.1','Species':'setosa'}]#? 表頭header = ['Petal.Length','Sepal.Length','Petal.Width','Sepal.Width','Species']printlen(data)withopen('E:/dst.csv','wb')asdstfile:#寫入方式選擇wb,否則有空行writer = csv.DictWriter(dstfile, fieldnames=header)? ? writer.writeheader()#? 寫入表頭writer.writerows(data)# 批量寫入dstfile.close()
上述代碼將數(shù)據(jù)整體寫入csv文件,如果數(shù)據(jù)量較多且想實(shí)時(shí)查看寫入了多少數(shù)據(jù)可以使用writerows函數(shù)。
讀取csv文件為DataFrame
代碼
# 讀取csv文件為DataFrameimportpandasaspddframe= pd.DataFrame.from_csv('E:/iris.csv')
也可以稍微曲折點(diǎn):
importcsvimportpandasaspdwithopen('E:/iris.csv')ascsvfile:? ? reader = csv.DictReader(csvfile, fieldnames=None)# fieldnames默認(rèn)為None,如果所讀csv文件沒有表頭,則需要指定list_1 = [eforeinreader]# 每行數(shù)據(jù)作為一個(gè)dict存入鏈表中csvfile.close()dfrme = pd.DataFrame.from_records(list_1)
從zip文件中讀取指定csv文件為DataFrame
dst.zip文件中包含有dst.csv和其它文件,現(xiàn)在在不解壓縮的情況下直接讀取dst.csv文件為DataFrame.
importpandas as pdimportzipfilez_file = zipfile.ZipFile('E:/dst.zip')dframe = pd.read_csv(z_file.open('dst.csv'))z_file.close()printdframe
DataFrame寫入csv文件
dfrme.to_csv('E:/dst.csv',index=False)# 不要每行的編號(hào)
讀取txt文件為DataFrame
importpandasaspdframe = pd.read_table(path, header=None, index_col=False, delimiter='\t', dtype=str)frame = pd.read_table(src_path, delimiter='|', header=None, error_bad_lines=False)
src_path:txt文件路徑
delimiter:字段分隔符
header:表頭
error_bad_lines: 是否忽略無法讀取的行(文件中部分行由于認(rèn)為事物造成讀取錯(cuò)誤)
dtype:數(shù)據(jù)讀入后的存儲(chǔ)類型