numpy中有兩個(gè)函數(shù)可以用來(lái)讀取文件,主要是txt文件, 下面主要來(lái)介紹這兩個(gè)函數(shù)的用法
第一個(gè)是loadtxt, 其一般用法為
numpy.loadtxt(fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
上面給出了loadtxt所有的關(guān)鍵字參數(shù), 這里我們可以來(lái)一一解釋并給出示例
這里我們使用的是jupyter notebook, 可以實(shí)現(xiàn)交互式的界面操作
%%writefile test.txt # 這是用來(lái)寫入文件的代碼1 2 3 4 2 3 4 53 4 5 64 5 6 7
首先給出最簡(jiǎn)單的loadtxt的代碼
import numpy as npa = np.loadtxt('test.txt')#最普通的loadtxtprint(a)實(shí)際上就是直接寫文件名, 其他關(guān)鍵字參數(shù)都是默認(rèn)的。輸出為
[[1. 2. 3. 4.]
[2. 3. 4. 5.]
[3. 4. 5. 6.]
[4. 5. 6. 7.]]
a為浮點(diǎn)數(shù)的原因?yàn)镻ython默認(rèn)的數(shù)字的數(shù)據(jù)類型為雙精度浮點(diǎn)數(shù)
%%writefile test.txtA B C1 2 34 5 67 8 9a = np.loadtxt('test1.txt', skiprows=1, dtype=int)print(a)這里的skiprows是指跳過前1行, 如果設(shè)置skiprows=2, 就會(huì)跳過前兩行, 這里的輸出為
[[1 2 3]
[4 5 6]
[7 8 9]]
%%writefile test.txtA B C1 2 3# AAA4 5 67 8 9a = np.loadtxt('test2.txt', dtype=int, skiprows=1, comments='#')print(a)這里的comment的是指, 如果行的開頭為#就會(huì)跳過該行, 這里輸出為
[[1 2 3]
[4 5 6]
[7 8 9]]
%%writefile test.txtA B C1, 2, 3# AA AAA4, 5, 67, 8, 9(a, b) = np.loadtxt('test.txt', dtype=int, skiprows=1, comments='#', delimiter=',', usecols=(0, 2), unpack=True)print(a, b)這里的usecols是指只使用0,2兩列, unpack是指會(huì)把每一列當(dāng)成一個(gè)向量輸出, 而不是合并在一起。
[1 4 7] [3 6 9]
最后介紹converters參數(shù), 這個(gè)是對(duì)數(shù)據(jù)進(jìn)行預(yù)處理的參數(shù), 我們可以先定義一個(gè)函數(shù), 這里的converters是一個(gè)字典, 表示第零列使用函數(shù)add_one來(lái)進(jìn)行預(yù)處理
def add_one(x):return int(x)+1#注意到這里使用的字符的數(shù)據(jù)結(jié)構(gòu)(a, b) = np.loadtxt('test.txt', dtype=int, skiprows=1, converters={0:add_one}, comments='#', delimiter=',', usecols=(0, 2), unpack=True)print(a, b)輸出結(jié)果為:
[2 5 8] [3 6 9]
補(bǔ)一個(gè)GitHub的jupyter-notebook鏈接...
https://github.com/ChangChunHe/PythonLearning/blob/master/Numpy/8.loadtxt_and_genfromtxt.ipynb
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選