NumPy學習筆記21. IO

NumPy IO

Numpy 可以讀寫磁盤上的文本數據或二進制數據。

NumPy 爲 ndarray 對象引入了一個簡單的文件格式:npy。

npy 文件用於存儲重建 ndarray 所需的數據、圖形、dtype 和其他信息。

常用的IO函數有:

  • load()和save()函數是讀寫文件數組數據的兩個主要函數,默認情況下,數組是未壓縮的原始二進制格式保存在擴展名爲 .npy 的文件中。
  • savez()函數用於將多個數組寫入文件,默認情況下,數組是以未壓縮的原始二進制格式保存在擴展名爲 .npz 的文件中。
  • loadtxt() 和 savetxt() 函數處理正常的文本文件(.txt 等)
numpy.save()
numpy.save(file, arr, allow_pickle=True, fix_imports=True)
# file:要保存的文件,擴展名爲 .npy,如果文件路徑末尾沒有擴展名 .npy,該擴展名會被自動加上
# arr: 要保存的數組
# allow_pickle: 可選,布爾值,允許使用 Python pickles 保存對象數組,Python 中的 pickle 用於在保存到磁盤文件或從磁盤文件讀取之前,對對象進行序列化和反序列化
# fix_imports: 可選,爲了方便 Pyhton2 中讀取 Python3 保存的數據
import numpy as np

a = np.array([1,2,3,4,5])

# 保存到outfile.npy文件上
np.save('outfile.npy',a)

# 保存到 outfile2.npy 文件上,如果文件路徑末尾沒有擴展名 .npy,該擴展名會被自動加上
np.save('outfile2',a)
import numpy as np

b = np.load('outfile.npy')
print(b)
[1 2 3 4 5]
numpy.savez()
numpy.savez(file, *args, **kwds)
# file:要保存的文件,擴展名爲 .npz,如果文件路徑末尾沒有擴展名 .npz,該擴展名會被自動加上
# args: 要保存的數組,可以使用關鍵字參數爲數組起一個名字,非關鍵字參數傳遞的數組會自動起名爲 arr_0, arr_1, …
# 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(r["arr_0"]) # 數組 a
print(r["arr_1"]) # 數組 b
print(r["sin_array"]) # 數組 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()

savetxt() 函數是以簡單的文本文件格式存儲數據,對應的使用 loadtxt() 函數來獲取數據

np.loadtxt(FILENAME, dtyoe = 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.]]

學習參考:

發佈了60 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章