Numpy 简明教程

I/O with NumPy

ndarray 对象可以保存到磁盘文件并从磁盘文件中加载。可用的 IO 函数有 −

The ndarray objects can be saved to and loaded from the disk files. The IO functions available are −

  1. load() and save() functions handle /numPy binary files (with npy extension)

  2. loadtxt() and savetxt() functions handle normal text files

NumPy 为 ndarray 对象引入了简单的文件格式。此 .npy 文件存储数据、形状、dtype 和在磁盘文件中重建 ndarray 所需的其他信息,以便即使文件在具有不同体系结构的另一台计算机上,也可以正确地检索数组。

NumPy introduces a simple file format for ndarray objects. This .npy file stores data, shape, dtype and other information required to reconstruct the ndarray in a disk file such that the array is correctly retrieved even if the file is on another machine with different architecture.

numpy.save()

numpy.save() 文件将输入数组存储在具有 npy 扩展名的磁盘文件中。

The numpy.save() file stores the input array in a disk file with npy extension.

import numpy as np
a = np.array([1,2,3,4,5])
np.save('outfile',a)

要从 outfile.npy 重建数组,请使用 load() 函数。

To reconstruct array from outfile.npy, use load() function.

import numpy as np
b = np.load('outfile.npy')
print b

它将生成如下输出:

It will produce the following output −

array([1, 2, 3, 4, 5])

save() 和 load() 函数接受一个额外的布尔参数 allow_pickles 。Python 中的 pickle 用于在保存到磁盘文件或从磁盘文件中读取之前对对象进行序列化和反序列化。

The save() and load() functions accept an additional Boolean parameter allow_pickles. A pickle in Python is used to serialize and de-serialize objects before saving to or reading from a disk file.

savetxt()

使用 savetxt()loadtxt() 函数以简单的文本文件格式存储和检索数组数据。

The storage and retrieval of array data in simple text file format is done with savetxt() and loadtxt() functions.

Example

import numpy as np

a = np.array([1,2,3,4,5])
np.savetxt('out.txt',a)
b = np.loadtxt('out.txt')
print b

它将生成如下输出:

It will produce the following output −

[ 1.  2.  3.  4.  5.]

savetxt() 和 loadtxt() 函数接受其他可选参数,例如标题、页脚和分隔符。

The savetxt() and loadtxt() functions accept additional optional parameters such as header, footer, and delimiter.