Numpy文件操作
Numpy可以以文本或二进制模式存储和读取数组数据。
np.save(file,array) : 以二进制文件存储数组数据,文件后缀为.npy,可自动添加后缀。
np.savez(file, *args, **kwds):以二进制文件不压缩存储多个数组数据到一个文件中,文件后缀为.npz。
np.savez_compressed(file, *args, **kwds):以二进制文件压缩存储多个数组数据到一个文件中,文件后缀为.npz。
np.load(file):从pickle 、.npy 、.npz 类型文件读取数组数据。
In [1]: import numpy as np
In [2]: arr = np.arange(10)
In [3]: arr
Out[3]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
#np.save(file,array) : Save an array to a binary file in NumPy ``.npy`` format.
In [4]: np.save('some_array',arr)
#np.load(file):Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.
In [6]: arr1 = np.load('some_array.npy')
In [7]: arr1
Out[7]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [8]: arr2 = np.arange(10).reshape(5,2)
In [9]: arr2
Out[9]:
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
#np.savez(file, *args, **kwds):Save several arrays into a single file in uncompressed ``.npz`` format.
In [14]: np.savez('array_archive2.npz',a = arr1,b=arr2)
In [15]: arch2 = np.load('array_archive2.npz')
In [17]: arch2['a']
Out[17]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [18]: arch2['b']
Out[18]:
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
#np.savez_compressed(file, *args, **kwds):Save several arrays into a single file in compressed ``.npz`` format.
In [19]: np.savez_compressed('array_compressed.npz',a = arr,b=arr2)
In [20]: arch3['a']
Out[20]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [21]: arch3['b']
Out[21]:
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])