NumPy 為 ndarray 對(duì)象引入了一個(gè)簡(jiǎn)單的文件格式: npy。
npy 文件用于存儲(chǔ)重建 ndarray 所需的數(shù)據(jù)、圖形、dtype 和其他信息。
常用的 IO 函數(shù)有:
load() 和 save() 函數(shù)是讀寫文件數(shù)組數(shù)據(jù)的兩個(gè)主要函數(shù),默認(rèn)情況下,數(shù)組是以未壓縮的原始二進(jìn)制格式保存在擴(kuò)展名為 .npy 的文件中。 savze() 函數(shù)用于將多個(gè)數(shù)組寫入文件,默認(rèn)情況下,數(shù)組是以未壓縮的原始二進(jìn)制格式保存在擴(kuò)展名為 .npz 的文件中。 loadtxt() 和 savetxt() 函數(shù)處理正常的文本文件(.txt 等) 參數(shù)說(shuō)明: 我們可以查看文件內(nèi)容: 可以看出文件是亂碼的,因?yàn)樗鼈兪?Numpy 專用的二進(jìn)制格式后的數(shù)據(jù)。 我們可以使用 load() 函數(shù)來(lái)讀取數(shù)據(jù)就可以正常顯示了: 輸出結(jié)果為: numpy.savez() 函數(shù)將多個(gè)數(shù)組保存到以 npz 為擴(kuò)展名的文件中。 參數(shù)說(shuō)明: 輸出結(jié)果為: savetxt() 函數(shù)是以簡(jiǎn)單的文本文件格式存儲(chǔ)數(shù)據(jù),對(duì)應(yīng)的使用 loadtxt() 函數(shù)來(lái)獲取數(shù)據(jù)。 參數(shù) delimiter 可以指定各種分隔符、針對(duì)特定列的轉(zhuǎn)換器函數(shù)、需要跳過(guò)的行數(shù)等。 輸出結(jié)果為: 使用 delimiter 參數(shù):numpy.save()
numpy.save(file, arr, allow_pickle=True, fix_imports=True)
import numpy as np
a = np.array([1,2,3,4,5])
# 保存到 test.npy 文件上
np.save('test.npy',a)
# 保存到 test1.npy 文件上,如果文件路徑末尾沒(méi)有擴(kuò)展名 .npy,該擴(kuò)展名會(huì)被自動(dòng)加上
np.save('test1.npy',a)
$ cat test.npy
?NUMPYv{'descr': '<i8', 'fortran_order': False, 'shape': (5,), }
$ cat test1.npy
?NUMPYv{'descr': '<i8', 'fortran_order': False, 'shape': (5,), }
import numpy as np
b = np.load('test.npy')
print (b)
[1 2 3 4 5]
np.savez
numpy.savez(file, *args, **kwds)
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.arange(0, 1.0, 0.1)
c = np.sin(b)
# c 使用了關(guān)鍵字參數(shù) sin_array
np.savez("nhooo.npz", a, b, sin_array = c)
r = np.load("nhooo.npz")
print(r.files) # 查看各個(gè)數(shù)組名稱
print(r["arr_0"]) # 數(shù)組 a
print(r["arr_1"]) # 數(shù)組 b
print(r["sin_array"]) # 數(shù)組 c
['sin_array', 'arr_0', 'arr_1']
[[1 2 3]
[4 5 6]]
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
[0. 0.09983342 0.19866933 0.29552021 0.38941834 0.47942554
0.56464247 0.64421769 0.71735609 0.78332691]
savetxt()
np.loadtxt(FILENAME, dtype=int, delimiter=' ')
np.savetxt(FILENAME, a, fmt="%d", delimiter=",")
import numpy as np
a = np.array([1,2,3,4,5])
np.savetxt('out.txt',a)
b = np.loadtxt('out.txt')
print(b)
[1. 2. 3. 4. 5.]
import numpy as np
a=np.arange(0,10,0.5).reshape(4,-1)
np.savetxt("out.txt",a,fmt="%d",delimiter=",") # 改為保存為整數(shù),以逗號(hào)分隔
b = np.loadtxt("out.txt",delimiter=",") # load 時(shí)也要指定為逗號(hào)分隔
print(b)
[[0. 0. 1. 1. 2.]
[2. 3. 3. 4. 4.]
[5. 5. 6. 6. 7.]
[7. 8. 8. 9. 9.]]