Numpy 能夠讀寫磁盤上的文本數據或二進制數據。數組
NumPy 爲 ndarray 對象引入了一個簡單的文件格式:npy。函數
npy 文件用於存儲重建 ndarray 所需的數據、圖形、dtype 和其餘信息。spa
經常使用的 IO 函數有:code
numpy.save() 函數將數組保存到以 .npy 爲擴展名的文件中。對象
numpy.save(file, arr, allow_pickle=True, fix_imports=True)
參數說明:blog
import numpy as np a = np.array([1, 2, 3, 4, 5]) np.save('outfile.npy', a) # 保存到 outfile.npy 文件上 np.save('outfile2', a) # 保存到 outfile2.npy 文件上,若是文件路徑末尾沒有擴展名 .npy,該擴展名會被自動加上
咱們能夠查看文件內容:it
$ cat outfile.npy ?NUMPYv{'descr': '<i8', 'fortran_order': False, 'shape': (5,), }
$ cat outfile2.npy ?NUMPYv{'descr': '<i8', 'fortran_order': False, 'shape': (5,), }
能夠看出文件是亂碼的,由於它們是 Numpy 專用的二進制格式後的數據。class
能夠使用 load() 函數來讀取數據就能夠正常顯示了:import
import numpy as np b = np.load('outfile.npy') print (b)
輸出結果爲:亂碼
[1 2 3 4 5]
numpy.savez() 函數將多個數組保存到以 npz 爲擴展名的文件中。
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 使用了關鍵字參數 sin_array np.savez("runoob.npz", a, b, sin_array=c) r = np.load("runoob.npz") print("查看各個數組名稱:",r.files) print('\n') print("數組 a:") print(r["arr_0"]) print('\n') print("數組 b:") print(r["arr_1"]) print('\n') print("數組 c:") print(r["sin_array"])
輸出結果爲:
查看各個數組名稱: ['sin_array', 'arr_0', 'arr_1']
數組 a:
[[1 2 3]
[4 5 6]]
數組 b:
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
數組 c:
[0. 0.09983342 0.19866933 0.29552021 0.38941834 0.47942554
0.56464247 0.64421769 0.71735609 0.78332691]
savetxt() 函數是以簡單的文本文件格式存儲數據,對應的使用 loadtxt() 函數來獲取數據。
np.loadtxt(FILENAME, dtype=int, delimiter=' ') np.savetxt(FILENAME, a, fmt="%d", delimiter=",")
參數 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.]
使用 delimiter 參數:
import numpy as np a=np.arange(0,10,0.5).reshape(4,-1)
np.savetxt("out.txt",a,fmt="%d",delimiter=",") # 改成保存爲整數,以逗號分隔 b = np.loadtxt("out.txt",delimiter=",") # load 時也要指定爲逗號分隔
print(b)
輸出結果爲:
[[0. 0. 1. 1. 2.] [2. 3. 3. 4. 4.] [5. 5. 6. 6. 7.] [7. 8. 8. 9. 9.]]