Python讀寫csv檔案的幾種方法 及 pandas.read_csv引數全解
''' Python讀寫csv檔案 逗號分隔值(Comma-Separated Values,CSV,有時也稱為字元分隔值,因為分隔字元也可以不是逗號), 其檔案以純文字形式儲存表格資料(數字和文字)。 純文字意味著該檔案是一個字元序列,不含必須像二進位制數字那樣被解讀的資料。 CSV檔案由任意數目的記錄組成,記錄間以某種換行符分隔;每條記錄由欄位組成,欄位間的分隔符是其它字元或字串, 最常見的是逗號或製表符。通常,所有記錄都有完全相同的欄位序列. 特點 讀取出的資料一般為字元型別,如果是數字需要人為轉換為數字 以行為單位讀取資料 列之間以半形逗號或製表符為分隔,一般為半形逗號 一般為每行開頭不空格,第一行是屬性列,資料列之間以間隔符為間隔無空格,行之間無空行。 行之間無空行十分重要,如果有空行或者資料集中行末有空格,讀取資料時一般會出錯,引發[list index out of range]錯誤。PS:已經被這個錯誤坑過很多次! ''' '''最常用的一種方法,利用pandas包''' import pandas as pd #任意的多組列表 a = [1,2,3] b = [4,5,6] #字典中的key值即為csv中列名 dataframe = pd.DataFrame({'a_name':a,'b_name':b}) #將DataFrame儲存為csv,index表示是否顯示行名,default=True dataframe.to_csv("test.csv",index=False,sep=',') '''同樣pandas也提供簡單的讀csv方法''' csv_data = pd.read_csv('test.csv') # 讀取訓練資料 print(csv_data.shape) ''' 會得到一個DataFrame型別的data,不熟悉處理方法可以參考pandas十分鐘入門 http://www.cnblogs.com/chaosimple/p/4153083.html ''' '''另一種方法用csv包,一行一行寫入''' import csv # python2可以用file替代open with open("test.csv","w") as csvfile: writer = csv.writer(csvfile) #先寫入columns_name writer.writerow(["index","csv_1","csv_2"]) #寫入多行用writerows writer.writerows([[0,1,3],[1,2,3],[2,3,4]]) '''csv.reader讀寫csv檔案''' import csv with open("test.csv","r") as csvfile: reader = csv.reader(csvfile) #這裡不需要readlines for line in reader: print (line) ''' 使用python I/O寫入和讀取CSV檔案 以下是將"birthweight.dat"低出生體重的dat檔案從作者源處下載下來,並且將其處理後儲存到csv檔案中的程式碼。 ''' import csv import os import numpy as np import requests birth_weight_file = 'birth_weight.csv' # download data and create data file if file does not exist in current directory # 如果當前資料夾下沒有birth_weight.csv資料集則下載dat檔案並生成csv檔案 if not os.path.exists(birth_weight_file): birthdata_url = 'https://github.com/nfmcclure/tensorflow_cookbook/raw/master/01_Introduction/07_Working_with_Data_Sources/birthweight_data/birthweight.dat' birth_file = requests.get(birthdata_url) birth_data = birth_file.text.split('\r\n') # split分割函式,以一行作為分割函式,windows中換行符號為'\r\n',每一行後面都有一個'\r\n'符號。 birth_header = birth_data[0].split('\t') # 每一列的標題,標在第一行,即是birth_data的第一個資料。並使用製表符作為劃分。 birth_data = [[float(x) for x in y.split('\t') if len(x) >= 1] for y in birth_data[1:] if len(y) >= 1] print(np.array(birth_data).shape) # (189, 9) # 此為list資料形式不是numpy陣列不能使用np,shape函式,但是我們可以使用np.array函式將list物件轉化為numpy陣列後使用shape屬性進行檢視。 with open(birth_weight_file, "w", newline='') as f: writer = csv.writer(f) writer.writerows([birth_header]) writer.writerows(birth_data) f.close() ''' # with open(birth_weight_file, "w") as f: 常見錯誤list index out of range 重點是 with open(birth_weight_file, "w", newline='') as f: 這個語句。 表示寫入csv檔案,如果不加上引數 newline='' 表示以空格作為換行符,則生成的表格中會出現空行。 不僅僅是用python I/O進行csv資料的讀寫時,利用其餘方法讀寫csv資料, 或者從網上下載好csv資料集後都需要檢視其每行後有沒有空格, 或者有沒有多餘的空行。避免不必要的錯誤~影響資料分析時的判斷。 ''' ''' 使用PythonI/O讀取csv檔案 使用python I/O方法進行讀取時即是新建一個List 列表然後按照先行後列的順序(類似C語言中的二維陣列) 將資料存進空的List物件中,如果需要將其轉化為numpy 陣列也可以使用np.array(List name)進行物件之間的轉化。 ''' birth_data = [] with open(birth_weight_file) as csvfile: csv_reader = csv.reader(csvfile) # 使用csv.reader讀取csvfile中的檔案 birth_header = next(csv_reader) # 讀取第一行每一列的標題 for row in csv_reader: # 將csv 檔案中的資料儲存到birth_data中 birth_data.append(row) birth_data = [[float(x) for x in row] for row in birth_data] # 將資料從string形式轉換為float形式 birth_data = np.array(birth_data) # 將list陣列轉化成array陣列便於檢視資料結構 birth_header = np.array(birth_header) print(birth_data.shape) # 利用.shape檢視結構。 print(birth_header.shape) ''' 使用Pandas讀取CSV檔案 ''' import pandas as pd csv_data = pd.read_csv('birth_weight.csv') # 讀取訓練資料 print(csv_data.shape) # (189, 9) N = 5 csv_batch_data = csv_data.tail(N) # 取後5條資料 print(csv_batch_data.shape) # (5, 9) train_batch_data = csv_batch_data[list(range(3, 6))] # 取這20條資料的3到5列值(索引從0開始) print(train_batch_data) print('使用Tensorflow讀取csv資料') import tensorflow as tf filename = 'birth_weight.csv' '''設定檔名佇列,這樣做能夠批量讀取資料夾中的檔案''' file_queue = tf.train.string_input_producer([filename]) '''使用tensorflow文字行閱讀器,並且設定忽略第一行''' reader = tf.TextLineReader(skip_header_lines=1) key, value = reader.read(file_queue) defaults = [[0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.]] # 設定列屬性的資料格式 LOW, AGE, LWT, RACE, SMOKE, PTL, HT, UI, BWT = tf.decode_csv(value, defaults) # 將讀取的資料編碼為我們設定的預設格式 vertor_example = tf.stack([AGE, LWT, RACE, SMOKE, PTL, HT, UI]) # 讀取得到的中間7列屬性為訓練特徵 vertor_label = tf.stack([BWT]) # 讀取得到的BWT值表示訓練標籤 ''' # 用於給取出的資料新增上batch_size維度,以批處理的方式讀出資料。 # 可以設定批處理資料大小,是否重複讀取資料,容量大小,佇列末尾大小,讀取執行緒等屬性。 ''' example_batch, label_batch = tf.train.shuffle_batch([vertor_example, vertor_label], batch_size=10, capacity=100, min_after_dequeue=10) # 初始化 Session with tf.Session() as sess: coord = tf.train.Coordinator() # 執行緒管理器 threads = tf.train.start_queue_runners(coord=coord) print(sess.run(tf.shape(example_batch))) # [10 7] print(sess.run(tf.shape(label_batch))) # [10 1] print(sess.run(example_batch)[3]) # [ 19. 91. 0. 1. 1. 0. 1.] coord.request_stop() coord.join(threads) ''' 方法語法:對於使用所有Tensorflow的I/O操作來說開啟和關閉執行緒管理器都是必要的操作 with tf.Session() as sess: coord = tf.train.Coordinator() # 執行緒管理器 threads = tf.train.start_queue_runners(coord=coord) # Your code here~ coord.request_stop() coord.join(threads) '''
csv.reader讀寫csv檔案''' import csv with open("test.csv","r") as csvfile: reader = csv.reader(csvfile) #這裡不需要readlines for line in reader: print (line) ''' 使用python I/O寫入和讀取CSV檔案 以下是將"birthweight.dat"低出生體重的dat檔案從作者源處下載下來,並且將其處理後儲存到csv檔案中的程式碼。 ''' import csv import os import numpy as np import requests birth_weight_file = 'birth_weight.csv' # download data and create data file if file does not exist in current directory # 如果當前資料夾下沒有birth_weight.csv資料集則下載dat檔案並生成csv檔案 if not os.path.exists(birth_weight_file): birthdata_url = 'https://github.com/nfmcclure/tensorflow_cookbook/raw/master/01_Introduction/07_Working_with_Data_Sources/birthweight_data/birthweight.dat' birth_file = requests.get(birthdata_url) birth_data = birth_file.text.split('\r\n') # split分割函式,以一行作為分割函式,windows中換行符號為'\r\n',每一行後面都有一個'\r\n'符號。 birth_header = birth_data[0].split('\t') # 每一列的標題,標在第一行,即是birth_data的第一個資料。並使用製表符作為劃分。 birth_data = [[float(x) for x in y.split('\t') if len(x) >= 1] for y in birth_data[1:] if len(y) >= 1] print(np.array(birth_data).shape) # (189, 9) # 此為list資料形式不是numpy陣列不能使用np,shape函式,但是我們可以使用np.array函式將list物件轉化為numpy陣列後使用shape屬性進行檢視。 with open(birth_weight_file, "w", newline='') as f: writer = csv.writer(f) writer.writerows([birth_header]) writer.writerows(birth_data) f.close() ''' # with open(birth_weight_file, "w") as f: 常見錯誤list index out of range 重點是 with open(birth_weight_file, "w", newline='') as f: 這個語句。 表示寫入csv檔案,如果不加上引數 newline='' 表示以空格作為換行符,則生成的表格中會出現空行。 不僅僅是用python I/O進行csv資料的讀寫時,利用其餘方法讀寫csv資料, 或者從網上下載好csv資料集後都需要檢視其每行後有沒有空格, 或者有沒有多餘的空行。避免不必要的錯誤~影響資料分析時的判斷。 ''' ''' 使用PythonI/O讀取csv檔案 使用python I/O方法進行讀取時即是新建一個List 列表然後按照先行後列的順序(類似C語言中的二維陣列) 將資料存進空的List物件中,如果需要將其轉化為numpy 陣列也可以使用np.array(List name)進行物件之間的轉化。 ''' birth_data = [] with open(birth_weight_file) as csvfile: csv_reader = csv.reader(csvfile) # 使用csv.reader讀取csvfile中的檔案 birth_header = next(csv_reader) # 讀取第一行每一列的標題 for row in csv_reader: # 將csv 檔案中的資料儲存到birth_data中 birth_data.append(row) birth_data = [[float(x) for x in row] for row in birth_data] # 將資料從string形式轉換為float形式 birth_data = np.array(birth_data) # 將list陣列轉化成array陣列便於檢視資料結構 birth_header = np.array(birth_header) print(birth_data.shape) # 利用.shape檢視結構。 print(birth_header.shape) ''' 使用Pandas讀取CSV檔案 ''' import pandas as pd csv_data = pd.read_csv('birth_weight.csv') # 讀取訓練資料 print(csv_data.shape) # (189, 9) N = 5 csv_batch_data = csv_data.tail(N) # 取後5條資料 print(csv_batch_data.shape) # (5, 9) train_batch_data = csv_batch_data[list(range(3, 6))] # 取這20條資料的3到5列值(索引從0開始) print(train_batch_data) print('使用Tensorflow讀取csv資料') import tensorflow as tf filename = 'birth_weight.csv' '''設定檔名佇列,這樣做能夠批量讀取資料夾中的檔案''' file_queue = tf.train.string_input_producer([filename]) '''使用tensorflow文字行閱讀器,並且設定忽略第一行''' reader = tf.TextLineReader(skip_header_lines=1) key, value = reader.read(file_queue) defaults = [[0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.]] # 設定列屬性的資料格式 LOW, AGE, LWT, RACE, SMOKE, PTL, HT, UI, BWT = tf.decode_csv(value, defaults) # 將讀取的資料編碼為我們設定的預設格式 vertor_example = tf.stack([AGE, LWT, RACE, SMOKE, PTL, HT, UI]) # 讀取得到的中間7列屬性為訓練特徵 vertor_label = tf.stack([BWT]) # 讀取得到的BWT值表示訓練標籤 ''' # 用於給取出的資料新增上batch_size維度,以批處理的方式讀出資料。 # 可以設定批處理資料大小,是否重複讀取資料,容量大小,佇列末尾大小,讀取執行緒等屬性。 ''' example_batch, label_batch = tf.train.shuffle_batch([vertor_example, vertor_label], batch_size=10, capacity=100, min_after_dequeue=10) # 初始化 Session with tf.Session() as sess: coord = tf.train.Coordinator() # 執行緒管理器 threads = tf.train.start_queue_runners(coord=coord) print(sess.run(tf.shape(example_batch))) # [10 7] print(sess.run(tf.shape(label_batch))) # [10 1] print(sess.run(example_batch)[3]) # [ 19. 91. 0. 1. 1. 0. 1.] coord.request_stop() coord.join(threads) ''' 方法語法:對於使用所有Tensorflow的I/O操作來說開啟和關閉執行緒管理器都是必要的操作 with tf.Session() as sess: coord = tf.train.Coordinator() # 執行緒管理器 threads = tf.train.start_queue_runners(coord=coord) # Your code here~ coord.request_stop() coord.join(threads) '''
附:pandas.read_csv引數全解
讀取CSV(逗號分割)檔案到DataFrame,也支援檔案的部分匯入和選擇迭代
引數:
filepath_or_buffer : str,pathlib。str, pathlib.Path, py._path.local.LocalPath or any object with a read() method (such as a file handle or StringIO)
可以是URL,可用URL型別包括:http, ftp, s3和檔案。對於多檔案正在準備中
本地檔案讀取例項:://localhost/path/to/table.csv
sep : str, default ‘,’
指定分隔符。如果不指定引數,則會嘗試使用逗號分隔。分隔符長於一個字元並且不是‘\s+’,將使用python的語法分析器。並且忽略資料中的逗號。正則表示式例子:'\r\t'
delimiter : str, default None
定界符,備選分隔符(如果指定該引數,則sep引數失效)
delim_whitespace : boolean, default False.
指定空格(例如’ ‘或者’ ‘)是否作為分隔符使用,等效於設定sep='\s+'。如果這個引數設定為Ture那麼delimiter 引數失效。
在新版本0.18.1支援
header : int or list of ints, default ‘infer’
指定行數用來作為列名,資料開始行數。如果檔案中沒有列名,則預設為0,否則設定為None。如果明確設定header=0 就會替換掉原來存在列名。header引數可以是一個list例如:[0,1,3],這個list表示將檔案中的這些行作為列標題(意味著每一列有多個標題),介於中間的行將被忽略掉(例如本例中的2;本例中的資料1,2,4行將被作為多級標題出現,第3行資料將被丟棄,dataframe的資料從第5行開始。)。
注意:如果skip_blank_lines=True 那麼header引數忽略註釋行和空行,所以header=0表示第一行資料而不是檔案的第一行。
names : array-like, default None
用於結果的列名列表,如果資料檔案中沒有列標題行,就需要執行header=None。預設列表中不能出現重複,除非設定引數mangle_dupe_cols=True。
index_col : int or sequence or False, default None
用作行索引的列編號或者列名,如果給定一個序列則有多個行索引。
如果檔案不規則,行尾有分隔符,則可以設定index_col=False 來是的pandas不適用第一列作為行索引。
usecols : array-like, default None
返回一個數據子集,該列表中的值必須可以對應到檔案中的位置(數字可以對應到指定的列)或者是字元傳為檔案中的列名。例如:usecols有效引數可能是 [0,1,2]或者是 [‘foo’, ‘bar’, ‘baz’]。使用這個引數可以加快載入速度並降低記憶體消耗。
as_recarray : boolean, default False
不贊成使用:該引數會在未來版本移除。請使用pd.read_csv(...).to_records()替代。
返回一個Numpy的recarray來替代DataFrame。如果該引數設定為True。將會優先squeeze引數使用。並且行索引將不再可用,索引列也將被忽略。
squeeze : boolean, default False
如果檔案值包含一列,則返回一個Series
prefix : str, default None
在沒有列標題時,給列新增字首。例如:新增‘X’ 成為 X0, X1, ...
mangle_dupe_cols : boolean, default True
重複的列,將‘X’...’X’表示為‘X.0’...’X.N’。如果設定為false則會將所有重名列覆蓋。
dtype : Type name or dict of column -> type, default None
每列資料的資料型別。例如 {‘a’: np.float64, ‘b’: np.int32}
engine : {‘c’, ‘python’}, optional
Parser engine to use. The C engine is faster while the python engine is currently more feature-complete.
使用的分析引擎。可以選擇C或者是python。C引擎快但是Python引擎功能更加完備。
converters : dict, default None
列轉換函式的字典。key可以是列名或者列的序號。
true_values : list, default None
Values to consider as True
false_values : list, default None
Values to consider as False
skipinitialspace : boolean, default False
忽略分隔符後的空白(預設為False,即不忽略).
skiprows : list-like or integer, default None
需要忽略的行數(從檔案開始處算起),或需要跳過的行號列表(從0開始)。
skipfooter : int, default 0
從檔案尾部開始忽略。 (c引擎不支援)
skip_footer : int, default 0
不推薦使用:建議使用skipfooter ,功能一樣。
nrows : int, default None
需要讀取的行數(從檔案頭開始算起)。
na_values : scalar, str, list-like, or dict, default None
一組用於替換NA/NaN的值。如果傳參,需要制定特定列的空值。預設為‘1.#IND’, ‘1.#QNAN’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘nan’`.
keep_default_na : bool, default True
如果指定na_values引數,並且keep_default_na=False,那麼預設的NaN將被覆蓋,否則新增。
na_filter : boolean, default True
是否檢查丟失值(空字串或者是空值)。對於大檔案來說資料集中沒有空值,設定na_filter=False可以提升讀取速度。
verbose : boolean, default False
是否列印各種解析器的輸出資訊,例如:“非數值列中缺失值的數量”等。
skip_blank_lines : boolean, default True
如果為True,則跳過空行;否則記為NaN。
parse_dates : boolean or list of ints or names or list of lists or dict, default False
- boolean. True -> 解析索引
- list of ints or names. e.g. If [1, 2, 3] -> 解析1,2,3列的值作為獨立的日期列;
- list of lists. e.g. If [[1, 3]] -> 合併1,3列作為一個日期列使用
- dict, e.g. {‘foo’ : [1, 3]} -> 將1,3列合併,並給合併後的列起名為"foo"
infer_datetime_format : boolean, default False
如果設定為True並且parse_dates 可用,那麼pandas將嘗試轉換為日期型別,如果可以轉換,轉換方法並解析。在某些情況下會快5~10倍。
keep_date_col : boolean, default False
如果連線多列解析日期,則保持參與連線的列。預設為False。
date_parser : function, default None
用於解析日期的函式,預設使用dateutil.parser.parser來做轉換。Pandas嘗試使用三種不同的方式解析,如果遇到問題則使用下一種方式。
1.使用一個或者多個arrays(由parse_dates指定)作為引數;
2.連線指定多列字串作為一個列作為引數;
3.每行呼叫一次date_parser函式來解析一個或者多個字串(由parse_dates指定)作為引數。
dayfirst : boolean, default False
DD/MM格式的日期型別
iterator : boolean, default False
返回一個TextFileReader 物件,以便逐塊處理檔案。
chunksize : int, default None
compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’
直接使用磁碟上的壓縮檔案。如果使用infer引數,則使用 gzip, bz2, zip或者解壓檔名中以‘.gz’, ‘.bz2’, ‘.zip’, or ‘xz’這些為字尾的檔案,否則不解壓。如果使用zip,那麼ZIP包中國必須只包含一個檔案。設定為None則不解壓。
新版本0.18.1版本支援zip和xz解壓
thousands : str, default None
千分位分割符,如“,”或者“."
decimal : str, default ‘.’
字元中的小數點 (例如:歐洲資料使用’,‘).
float_precision : string, default None
Specifies which converter the C engine should use for floating-point values. The options are None for the ordinary converter, high for the high-precision converter, and round_trip for the round-trip converter.
指定
lineterminator : str (length 1), default None
行分割符,只在C解析器下使用。
quotechar : str (length 1), optional
引號,用作標識開始和解釋的字元,引號內的分割符將被忽略。
quoting : int or csv.QUOTE_* instance, default 0
控制csv中的引號常量。可選 QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3)
doublequote : boolean, default True
雙引號,當單引號已經被定義,並且quoting 引數不是QUOTE_NONE的時候,使用雙引號表示引號內的元素作為一個元素使用。
escapechar : str (length 1), default None
當quoting 為QUOTE_NONE時,指定一個字元使的不受分隔符限值。
comment : str, default None
標識著多餘的行不被解析。如果該字元出現在行首,這一行將被全部忽略。這個引數只能是一個字元,空行(就像skip_blank_lines=True)註釋行被header和skiprows忽略一樣。例如如果指定comment='#' 解析‘#empty\na,b,c\n1,2,3’ 以header=0 那麼返回結果將是以’a,b,c'作為header。
encoding : str, default None
dialect : str or csv.Dialect instance, default None
如果沒有指定特定的語言,如果sep大於一個字元則忽略。具體檢視csv.Dialect 文件
tupleize_cols : boolean, default False
Leave a list of tuples on columns as is (default is to convert to a Multi Index on the columns)
error_bad_lines : boolean, default True
如果一行包含太多的列,那麼預設不會返回DataFrame ,如果設定成false,那麼會將改行剔除(只能在C解析器下使用)。
warn_bad_lines : boolean, default True
如果error_bad_lines =False,並且warn_bad_lines =True 那麼所有的“bad lines”將會被輸出(只能在C解析器下使用)。
low_memory : boolean, default True
分塊載入到記憶體,再低記憶體消耗中解析。但是可能出現型別混淆。確保型別不被混淆需要設定為False。或者使用dtype 引數指定型別。注意使用chunksize 或者iterator 引數分塊讀入會將整個檔案讀入到一個Dataframe,而忽略型別(只能在C解析器中有效)
buffer_lines : int, default None
不推薦使用,這個引數將會在未來版本移除,因為他的值在解析器中不推薦使用
compact_ints : boolean, default False
不推薦使用,這個引數將會在未來版本移除
如果設定compact_ints=True ,那麼任何有整數型別構成的列將被按照最小的整數型別儲存,是否有符號將取決於use_unsigned 引數
use_unsigned : boolean, default False
不推薦使用:這個引數將會在未來版本移除
如果整數列被壓縮(i.e. compact_ints=True),指定被壓縮的列是有符號還是無符號的。
memory_map : boolean, default False
如果使用的檔案在記憶體內,那麼直接map檔案使用。使用這種方式可以避免檔案再次進行IO操作。