溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python中numpy.loadtxt()讀取txt文件的案例

發(fā)布時(shí)間:2020-11-03 09:43:25 來源:億速云 閱讀:1820 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)Python中numpy.loadtxt()讀取txt文件的案例的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考。一起跟隨小編過來看看吧。

讀取txt文件我們通常使用 numpy 中的 loadtxt()函數(shù)

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

注:loadtxt的功能是讀入數(shù)據(jù)文件,這里的數(shù)據(jù)文件要求每一行數(shù)據(jù)的格式相同。

也就是說對于下面這樣的數(shù)據(jù)是不符合條件的:

123

1 2 4 3 5

接下來舉例講解函數(shù)的功能:

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.]]

數(shù)組中的數(shù)都為浮點(diǎn)數(shù),原因?yàn)镻ython默認(rèn)的數(shù)字的數(shù)據(jù)類型為雙精度浮點(diǎn)數(shù) 

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=‘#’:如果行的開頭為#就會(huì)跳過該行

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兩列,參數(shù)類型為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是指會(huì)把每一列當(dāng)成一個(gè)向量輸出, 而不是合并在一起。 如果unpack為false或者參數(shù)的話輸出結(jié)果如下:

[[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:數(shù)據(jù)之間的分隔符。如使用逗號","。

6、converters:對數(shù)據(jù)進(jìn)行預(yù)處理

def add_one(x):    return int(x)+1    #注意到這里使用的字符的數(shù)據(jù)結(jié)構(gòu) 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    #注意到這里使用的字符的數(shù)據(jù)結(jié)構(gòu) a = np.loadtxt('test.txt', dtype=int, skiprows=1, converters={0:add_one}, comments='#', delimiter=',', usecols=(0, 2), unpack=True) print a

感謝各位的閱讀!關(guān)于Python中numpy.loadtxt()讀取txt文件的案例就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI