1. 程式人生 > >matplotlib資料視覺化分析(2)-- numpy將陣列儲存到檔案

matplotlib資料視覺化分析(2)-- numpy將陣列儲存到檔案

1 陣列以二進位制的格式儲存

np.save 和 np.load 是讀寫磁碟資料的兩個主要函式。預設情況下,陣列以未壓縮的原始二進位制格式儲存在副檔名為 npy 的檔案中,以陣列 a 為例:

# coding:utf-8
import numpy as np

c = np.random.randint(0, 101, 10)
print c
np.save('c.npy', c)
c1 = np.load('c.npy')
print c1

利用這種方法,檔案的字尾名字一定會被設定為 .npy

2. 存取文字檔案

使用 np.savetxt 和 np.loadtxt 只能讀寫 1 維和 2 維 的陣列 np.savetxt :將陣列寫入以某種分隔符隔開的文字檔案中 np.loadtxt : 指定某種分隔符,將文字檔案讀入到陣列中

# coding:utf-8
import numpy as np

c = np.random.randint(0, 101, 10)
print c
np.savetxt('c.txt', c)
c1 = np.loadtxt('c.txt', delimiter=',')
print c1

儲存為二進位制檔案

使用陣列的 tofile 函式可以方便地把陣列中資料以二進位制的格式寫進檔案

# coding:utf-8
import numpy as np

c = np.random.randint(0, 101, 10)
print c
c.tofile('c.bin')
c1 = np.fromfile('c.bin', dtype=None)
print c1

該方法與np.save有幾點區別:

  1. tofile函式只能將陣列儲存為二進位制檔案,檔案字尾名沒有固定要求。這種儲存方法對資料讀取有要求,np.fromfile 需要手動指定讀出來的資料的的dtype,如果指定的格式與儲存時的不一致,則讀出來的就是錯誤的資料。
  2. tofile函式不能儲存當前資料的行列資訊,不管陣列的排列順序是C語言格式的還是Fortran語言格式,統一使用C語言格式輸出。因此使用 np.fromfile 讀出來的資料是一維陣列,需要利用reshape指定行列資訊。

舉例:

# coding:utf-8
import numpy as np

a = np.arange(0, 12)
a.shape = 3, 4
print a
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
a.tofile('a.bin')
b = np.fromfile('a.bin', dtype=np.float)
# 這是讀入的資料是錯誤的
print b
print a.dtype
# int64

# 按照 int64 型別讀入資料
b = np.fromfile('a.bin', dtype=np.int64)
print b
# 按照 a 的 shape 修改 b 的 shape
b.shape = 3, 4
print b