1. 程式人生 > >#Python第三方模組學習(二)——numpy中loadtxt函式用法詳解

#Python第三方模組學習(二)——numpy中loadtxt函式用法詳解

本篇系轉載文章,並在原文的基礎上補充引數delimeter的說明

umpy中有兩個函式可以用來讀取檔案,主要是txt檔案, 下面主要來介紹這兩個函式的用法

第一個是loadtxt, 其一般用法為

numpy.loadtxt(fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)

上面給出了loadtxt所有的關鍵字引數, 這裡我們可以來一一解釋並給出示例

這裡我們使用的是jupyter notebook, 可以實現互動式的介面操作

%%writefile test.txt # 這是用來寫入檔案的程式碼
1 2 3 4 
2 3 4 5
3 4 5 6
4 5 6 7

首先給出最簡單的loadtxt的程式碼

import numpy as np
a = np.loadtxt('test.txt')#最普通的loadtxt
print(a)

實際上就是直接寫檔名, 其他關鍵字引數都是預設的。輸出為

[[1. 2. 3. 4.]
 [2. 3. 4. 5.]
 [3. 4. 5. 6.]
 [4. 5. 6. 7.]]
a為浮點數的原因為Python預設的數字的資料型別為雙精度浮點數

複製程式碼

%%writefile test.txt
A B C
1 2 3
4 5 6
7 8 9

a = np.loadtxt('test1.txt', skiprows=1, dtype=int)
print(a)

複製程式碼

這裡的skiprows是指跳過前1行, 如果設定skiprows=2, 就會跳過前兩行,  這裡的輸出為

[[1 2 3]
 [4 5 6]
 [7 8 9]]

複製程式碼

%%writefile test.txt
A B C
1 2 3
# AAA
4 5 6
7 8 9

a = np.loadtxt('test2.txt', dtype=int, skiprows=1, comments='#')
print(a)

複製程式碼

這裡的comment的是指, 如果行的開頭為#就會跳過該行, 這裡輸出為

[[1 2 3]
 [4 5 6]
 [7 8 9]]

複製程式碼

%%writefile test.txt
A B C
1, 2, 3
# AA AAA
4, 5, 6
7, 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是指會把每一列當成一個向量輸出, 而不是合併在一起。

[1 4 7] [3 6 9]

最後介紹converters引數, 這個是對資料進行預處理的引數, 我們可以先定義一個函式, 這裡的converters是一個字典, 表示第零列使用函式add_one來進行預處理

複製程式碼

def add_one(x):
return int(x)+1#注意到這裡使用的字元的資料結構
(a, b) = np.loadtxt('test.txt', dtype=int, skiprows=1, converters={0:add_one}, comments='#', delimiter=',', usecols=(0, 2), unpack=True)
print(a, b)

複製程式碼

輸出結果為:
[2 5 8] [3 6 9]