Python中的numpy.load()用於從文本文件加載數據,目的是成為簡單文本文件的快速閱讀器。
請注意,文本文件中的每一行必須具有相同數量的值。
用法:numpy.loadtxt(fname, dtype=’float’, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
參數:
fname :要讀取的文件,文件名或生成器。如果文件擴展名是.gz或.bz2,則首先將文件解壓縮。請注意,生成器應返回Python 3k的字節字符串。
dtype :結果數組的數據類型;默認值:浮點數。如果這是結構化數據類型,則結果數組將為一維,並且每一行將被解釋為數組的元素。
delimiter :用於分隔值的字符串。默認情況下,這是任何空格。
converters :字典將列號映射到將該列轉換為浮點數的函數。例如,如果第0列是日期字符串:轉換器= {0:datestr2num}。默認值:無。
skiprows :跳過第一行默認值:0
返回:ndarray
代碼1:
# Python program explaining
# loadtxt() function
import numpy as geek
# StringIO behaves like a file object
from io import StringIO
c = StringIO("0 1 2 \n3 4 5")
d = geek.loadtxt(c)
print(d)
輸出:
[[ 0. 1. 2.] [ 3. 4. 5.]]
代碼2:
# Python program explaining
# loadtxt() function
import numpy as geek
# StringIO behaves like a file object
from io import StringIO
c = StringIO("1, 2, 3\n4, 5, 6")
x, y, z = geek.loadtxt(c, delimiter =', ', usecols =(0, 1, 2),
unpack = True)
print("x is: ", x)
print("y is: ", y)
print("z is: ", z)
輸出:
x is: [ 1. 4.] y is: [ 2. 5.] z is: [ 3. 6.]
代碼3:
# Python program explaining
# loadtxt() function
import numpy as geek
# StringIO behaves like a file object
from io import StringIO
d = StringIO("M 21 72\nF 35 58")
e = geek.loadtxt(d, dtype ={'names': ('gender', 'age', 'weight'),
'formats': ('S1', 'i4', 'f4')})
print(e)
輸出:
[(b'M', 21, 72.) (b'F', 35, 58.)]
相關用法
注:本文由純淨天空篩選整理自ArkadipGhosh大神的英文原創作品 numpy.loadtxt() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。