來源:https://www.py.cn/jishu/jichu/20407.html
為了方便使用和記憶,有時候我們會把 numpy.loadtxt() 縮寫成np.loadtxt() ,本篇文章主要講解用它來讀取txt文件。
讀取txt文件我們通常使用 numpy 中的 loadtxt()函數
numpy.loadtxt(fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
注:loadtxt的功能是讀入數據文件,這里的數據文件要求每一行數據的格式相同。
也就是說對於下面這樣的數據是不符合條件的:
123
1 2 4 3 5
接下來舉例講解函數的功能:
1、簡單的讀取
test.txt
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
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.]]
數組中的數都為浮點數,原因為Python默認的數字的數據類型為雙精度浮點數
2、skiprows=n:指跳過前n行
test.txt
A B C D
2 3 4 5
3 4 5 6
4 5 6 7
a = np.loadtxt('test.txt', skiprows=1, dtype=int) print(a)
輸出:
[[2 3 4 5]
[3 4 5 6]
[4 5 6 7]]
3、comment=‘#’:如果行的開頭為#就會跳過該行
test.txt
A B C D
2 3 4 5
3 4 5 6
#A B C D
4 5 6 7
a = np.loadtxt('test.txt', skiprows=1, dtype=int, comments='#') print(a)
輸出:
[[2 3 4 5]
[3 4 5 6]
[4 5 6 7]]
4、usecols=[0,2]:是指只使用0,2兩列,參數類型為list
a = np.loadtxt('test.txt', skiprows=1, dtype=int, comments='#',usecols=(0, 2), unpack=True) print(a)
輸出:
[[2 3 4]
[4 5 6]]
unpack是指會把每一列當成一個向量輸出, 而不是合並在一起。 如果unpack為false或者參數的話輸出結果如下:
[[2 4]
[3 5]
[4 6]]
test.txt
A, B, C, D
2, 3, 4, 5
3, 4, 5, 6
#A B C D
4, 5, 6, 7
5、delimiter:數據之間的分隔符。如使用逗號","。
6、converters:對數據進行預處理
def add_one(x): return int(x)+1 #注意到這里使用的字符的數據結構 a = np.loadtxt('test.txt', dtype=int, skiprows=1, converters={0:add_one}, comments='#', delimiter=',', usecols=(0, 2), unpack=True) print a
def add_one(x): return int(x)+1 #注意到這里使用的字符的數據結構 a = np.loadtxt('test.txt', dtype=int, skiprows=1, converters={0:add_one}, comments='#', delimiter=',', usecols=(0, 2), unpack=True) print a
以上就是numpy.loadtxt() 讀取txt文件的幾種方法。