python:保存N维数组(ndarray)到本地文件

需求

实际程序中,往往需要将运算结果(ndarray类型)保存到本地,以便进行后续的数据分析。利用numpy.savetxt可以保存1维或2维数据到txt文件中,但无法保存3维以上的数据。比如对一个图像库提取的图像特征。

此时可以用numpy.savez方法来保存3维以上的数据。

接口

保存数据用numpy.savez

  • 可以保存任意多个N维数组,有两种保存方式:
    1.用*args方式,比如np.savez('data',d1,d2,d3),它将会以以arr_0,arr_1,arr_2来表示d1,d2,d3的名字,用于访问数据时用。
    2.用**kwds方式,比如np.savez('data',d1=d1,d2=d2,d3=d3),即指定了数组名,用于访问数据时用。
  • 保存后的本地文件为npz格式。

需要载入数据时用np.load(file)方法

  • 载入后的对象为NpzFile对象,类似一个字典。可以通过NpzFile.files来查看该文件中,有哪些数据。进而再通过类似字典索引的方式来访问数据,详情见实例。
Signature: np.savez(file, *args, **kwds)
Docstring:
Save several arrays into a single file in uncompressed ``.npz`` format.

If arguments are passed in with no keywords, the corresponding variable
names, in the ``.npz`` file, are 'arr_0', 'arr_1', etc. If keyword
arguments are given, the corresponding variable names, in the ``.npz``
file will match the keyword names.

Parameters
----------
file : str or file
    Either the file name (string) or an open file (file-like object)
    where the data will be saved. If file is a string or a Path, the
    ``.npz`` extension will be appended to the file name if it is not
    already there.
args : Arguments, optional
    Arrays to save to the file. Since it is not possible for Python to
    know the names of the arrays outside `savez`, the arrays will be saved
    with names "arr_0", "arr_1", and so on. These arguments can be any
    expression.
kwds : Keyword arguments, optional
    Arrays to save to the file. Arrays will be saved in the file with the
    keyword names.

实例

实例1:用*args方式保存数据

In [48]: d1 = np.random.randint(0,100,(2,2,2))

In [49]: d1
Out[49]: 
array([[[12, 72],
        [60, 41]],

       [[ 2,  6],
        [62, 53]]])

In [50]: d2, d3 = d1*10, d1*100

In [51]: np.savez('data',d1,d2,d3)

In [52]: data = np.load('data.npz')

In [53]: data.files
Out[53]: ['arr_0', 'arr_1', 'arr_2']

In [54]: data['arr_0']
Out[54]: 
array([[[12, 72],
        [60, 41]],

       [[ 2,  6],
        [62, 53]]])

In [55]: data['arr_1']
Out[55]: 
array([[[120, 720],
        [600, 410]],

       [[ 20,  60],
        [620, 530]]])

In [56]: data['arr_2']
Out[56]: 
array([[[1200, 7200],
        [6000, 4100]],

       [[ 200,  600],
        [6200, 5300]]])

实例2:用**kwds方式保存数据


In [57]: np.savez('data2',d1=d1,d2=d2,d3=d3) # 等价于
# d = {'d1':d1,'d2':d2,'d3':d3}
# np.savez('data2',**d)

In [58]: data2 = np.load('data2.npz')

In [59]: data2.files
Out[59]: ['d1', 'd2', 'd3']

In [62]: data2['d1']
Out[62]: 
array([[[12, 72],
        [60, 41]],

       [[ 2,  6],
        [62, 53]]])

In [63]: data2['d2']
Out[63]: 
array([[[120, 720],
        [600, 410]],

       [[ 20,  60],
        [620, 530]]])

In [64]: data2['d3']
Out[64]: 
array([[[1200, 7200],
        [6000, 4100]],

       [[ 200,  600],
        [6200, 5300]]])

你可能感兴趣的:(python,python)