numpy教程:基本输入输出和文件输入输出Input and output

http://blog.csdn.net/pipisorry/article/details/39088003

基本输入输出和文件输入输出

文件名和文件对象

本节介绍所举的例子都是传递的文件名,也可以传递已经打开的文件对象.

例如对于load和save函数来说,如果使用文件对象的话,可以将多个数组储存到一个npy文件中:

>>> a = np.arange(8)
>>> b = np.add.accumulate(a)
>>> c = a + b
>>> f = file("result.npy", "wb")
>>> np.save(f, a) # 顺序将a,b,c保存进文件对象f
>>> np.save(f, b)
>>> np.save(f, c)
>>> f.close()
>>> f = file("result.npy", "rb")
>>> np.load(f) # 顺序从文件对象f中读取内容
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> np.load(f)
array([ 0,  1,  3,  6, 10, 15, 21, 28])
>>> np.load(f)
array([ 0,  2,  5,  9, 14, 20, 27, 35])

文件对象写入时的注意事项

numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=’‘, footer=’‘, comments=’#‘)
Save an array to a text file.

np.savetxt(输出文件名,矩阵名)

输出文件名应为二进制写入:

doc_word_mat_file = open('./filename.txt', 'wb')

否则出错:

    savetxt(doc_word_mat_file, doc_word_mat) ...     fh.write(asbytes(format % tuple(row) + newline))
TypeError: must be str, not bytes

所以推荐不要使用文件对象写入,用文件名写入

皮皮blog


numpy数组输出选项设置

在屏幕上输出数组:print(mat1)

Text formatting options

set_printoptions([precision, threshold, ...])Set printing options.
get_printoptions()Return the current print options.
set_string_function(f[, repr])Set a Python function to be used when pretty printing arrays.

numpy数组打印效果设置

多维数组强制打印全部输出

如果一个数组用来打印太大了,NumPy自动省略中间部分而只打印角落。禁用NumPy的这种行为并强制打印整个数组,你可以设置printoptions参数来更改打印选项。

np.set_printoptions(threshold=np.NaN)

threshold : int, optional   Total number of array elements which trigger summarizationrather than full repr (default 1000).

使用set_printoptions设置输出精度

np.set_printoptions(precision=3) print(x) # [ 0.078 0.48 0.413 0.83 0.776 0.102 0.513 0.462 0.335 0.712]

但是怎么没办法输出原本数据的最精确精度,如有的数据是10位小数,有的是8位,输出不好控制precision为多少好。精度过高就会出错。

这时可以使用array.astype(str)转换成字符串输出。如

[['40.731354990929475' '-74.00363118575608']
  ['40.731508' '-74.0031859561163']]

suppress消除小的数字使用科学记数法

y=np.array([1.5e-10,1.5,1500]) print(y) # [ 1.500e-10 1.500e+00 1.500e+03] np.set_printoptions(suppress=True) print(y) # [ 0. 1.5 1500. ]
在本地应用打印选项 中, 你可以使用 contextmanager ...

formatter参数允许你指定一个格式为每个类型的函数(注意结尾补0了)

np.set_printoptions(formatter={'float': '{: 0.3f}'.format}) print(x)
[ 0.078 0.480 0.413 0.830 0.776 0.102 0.513 0.462 0.335 0.712]

奇怪的方式

print(np.char.mod('%4.2f', eigen_value))
[ Pretty-printing of numpy.array][ numpy.array的效果 ]

numpy输出精度局部控制

@contextmanager
def np_printoptions(*args, **kwargs):
    '''
    numpy本地应用打印选项,如:
    with np_printoptions(precision=3, suppress=True):
        print(x1)
    '''
    original = np.get_printoptions()
    np.set_printoptions(*args, **kwargs)
    yield  np.set_printoptions(**original)

皮皮blog


numpy文件存取

NumPy提供了多种文件操作函数方便我们存取数组内容。

文件存取的格式:二进制和文本。二进制格式的文件又分为NumPy专用的格式化二进制类型和无格式类型。

Numpy binary files (NPY, NPZ)

load(file[, mmap_mode, allow_pickle, ...])Load arrays or pickled objects from .npy, .npz or pickled files.
save(file, arr[, allow_pickle, fix_imports])Save an array to a binary file in NumPy .npy format.
savez(file, *args, **kwds)Save several arrays into a single file in uncompressed .npz format.
savez_compressed(file, *args, **kwds)Save several arrays into a single file in compressed .npz format.

The format of these binary file types is documented inhttp://docs.scipy.org/doc/numpy/neps/npy-format.html

numpy.load和numpy.save函数(推荐在不需要查看保存数据的情况下使用)

以NumPy专用的二进制类型保存数据,这两个函数会自动处理元素类型和shape等信息,使用它们读写数组就方便多了,但是numpy.save输出的文件很难和其它语言编写的程序读入:

>>> np.save("a.npy", a)
>>> c = np.load( "a.npy" )
>>> c
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Note:

1. 文件要保存为.npy文件类型,否则会出错

2. 保存为numpy专用二进制格式后,就不能用notepad++打开(乱码)看了,这是相对tofile内建函数不好的一点

numpy.savez函数

如果你想将多个数组保存到一个文件中的话,可以使用numpy.savez函数。savez函数的第一个参数是文件名,其后的参数都是需要保存的数组,也可以使用关键字参数为数组起一个名字,非关键字参数传递的数组会自动起名为arr_0, arr_1, ...。savez函数输出的是一个压缩文件(扩展名为npz),其中每个文件都是一个save函数保存的npy文件,文件名对应于数组名。load函数自动识别npz文件,并且返回一个类似于字典的对象,可以通过数组名作为关键字获取数组的内容:

>>> a = np.array([[1,2,3],[4,5,6]])
>>> b = np.arange(0, 1.0, 0.1)
>>> c = np.sin(b)
>>> np.savez("result.npz", a, b, sin_array = c)
>>> r = np.load("result.npz")
>>> r["arr_0"] # 数组a
array([[1, 2, 3],
       [4, 5, 6]])
>>> r["arr_1"] # 数组b
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])
>>> r["sin_array"] # 数组c
array([ 0.        ,  0.09983342,  0.19866933,  0.29552021,  0.38941834,
        0.47942554,  0.56464247,  0.64421769,  0.71735609,  0.78332691])

如果你用解压软件打开result.npz文件的话,会发现其中有三个文件:arr_0.npy, arr_1.npy, sin_array.npy,其中分别保存着数组a, b, c的内容。

皮皮blog



numpy读取文本文件Text files

loadtxt(fname[, dtype, comments, delimiter, ...])Load data from a text file.
savetxt(fname, X[, fmt, delimiter, newline, ...])Save an array to a text file.
genfromtxt(fname[, dtype, comments, ...])Load data from a text file, with missing values handled as specified.
fromregex(file, regexp, dtype)Construct an array from a text file, using regular expression parsing.
fromstring(string[, dtype, count, sep])A new 1-D array initialized from raw binary or text data in a string.
ndarray.tofile(fid[, sep, format])Write array to a file as text or binary (default).
ndarray.tolist()Return the array as a (possibly nested) list.

numpy.savetxt和numpy.loadtxt(推荐需要查看保存数据时使用)

使用numpy.savetxt和numpy.loadtxt可以读写1维和2维的数组:

np.loadtxt(FILENAME, dtype=int, delimiter=' ')

numpy.loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)

使用结构数组读入文件
persontype = np.dtype({'names':['name', 'age', 'weight', 'height'],
                       'formats':['S32','i', 'f', 'f']})
data = np.loadtxt(f, delimiter=",", dtype=persontype)

np.savetxt("a.txt",a, fmt="%d",delimiter=",")

>>> a = np.arange(0,12,0.5).reshape(4,-1)
>>> np.savetxt("a.txt", a) # 缺省按照'%.18e'格式保存数据,以空格分隔
>>> np.loadtxt("a.txt")

>>> np.savetxt("a.txt", a, fmt="%d", delimiter=",") #改为保存为整数,以逗号分隔
>>> np.loadtxt("a.txt",delimiter=",") # 读入的时候也需要指定逗号分隔
array([[  0.,   0.,   1.,   1.,   2.,   2.],
       [  3.,   3.,   4.,   4.,   5.,   5.],
       [  6.,   6.,   7.,   7.,   8.,   8.],
       [  9.,   9.,  10.,  10.,  11.,  11.]])

Note:savetxt缺省按照'%.18e'格式保存数据, 可以修改保存格式为‘%.8f'(小数点后保留8位的浮点数), ’%d'(整数)等等

np.savetxt保存中文字符串数组

实际上是不可以的,因为默认是wb格式保存,这样就是保存为bytes,py3中的str又是unicode,这样就算保存下来了,也并看不了保存下来的中文是什么。

如:

s = np.array([['工', '1'], ['q', '1']])
print(s)
s = np.char.encode(s,'utf-8')
np.savetxt('/tmp/1.txt', s, fmt='%s')
文件中只会这样显示:b'\xe5\xb7\xa5' b'1'
b'q' b'1'

所以有中文的话,而且实在想看文件中的内容,只有使用普通保存方法保存了:with open() as f: f.write(lines)什么的。

[Write numpy unicode array to a text file]

loadtxt出错

1 numpy.loadtxt读入的字符串总是bytes格式,总是在前面加了一个b

原因:np.loadtxt and np.genfromtxt operate in byte mode, which is the default string type in Python 2. But Python 3 uses unicode, and marks bytestrings with this b.  numpy.loadtxt中也声明了:Note that generators should return byte strings for Python 3k.

解决:使用numpy.loadtxt从文件读取字符串,最好使用这种方式np.loadtxt(filename, dtype=bytes).astype(str)

['b' character added when using numpy loadtxt]

[numpy.loadtxt]

总结:

载入txt文件:numpy.loadtxt()/numpy.savetxt()

智能导入文本/csv文件:numpy.genfromtxt()/numpy.recfromcsv()

高速,有效率但numpy特有的二进制格式:numpy.save()/numpy.load()

2 ValueError: Wrong number of columns at line 78446

原因是数据问题,可能前面的数据都是3列而78446却是2或4列等等。

查看数据nl data_test6.txt | grep -C 3 78446

numpy.genfromtxt

import numpy as np
np.genfromtxt('filename', dtype= None)
# array([(1, 2.0, 'buckle_my_shoe'), (3, 4.0, 'margery_door')],
#  dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', '|S14')])

皮皮blog


Raw binary files

fromfile(file[, dtype, count, sep])Construct an array from data in a text or binary file.
ndarray.tofile(fid[, sep, format])Write array to a file as text or binary (default).

tofile和fromfile数组内建函数(not recommend)

使用数组的方法函数tofile可以方便地将数组中数据以二进制的格式写进文件。tofile输出的数据没有格式,因此用numpy.fromfile读回来的时候需要自己格式化数据:

>>> a = np.arange(0,12)
>>> a.shape = 3,4
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> a.tofile("a.bin")
>>> b = np.fromfile("a.bin", dtype=np.float) # 按照float类型读入数据
>>> b # 读入的数据是错误的
array([  2.12199579e-314,   6.36598737e-314,   1.06099790e-313,
         1.48539705e-313,   1.90979621e-313,   2.33419537e-313])
>>> a.dtype # 查看a的dtype
dtype('int32')
>>> b = np.fromfile("a.bin", dtype=np.int32) # 按照int32类型读入数据
>>> b # 数据是一维的
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
>>> b.shape = 3, 4 # 按照a的shape修改b的shape
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Note:

1. 读入的时候设置正确的dtype和shape才能保证数据一致。并且tofile函数不管数组的排列顺序是C语言格式的还是Fortran语言格式的,统一使用C语言格式输出。

2. sep关键字参数:此外如果fromfile和tofile函数调用时指定了sep关键字参数的话,数组将以文本格式输入输出。{这样就可以通过notepad++打开查看, 不过数据是一行显示,不便于查看}

user_item_mat.tofile(user_item_mat_filename, sep=' ')
皮皮blog


String formatting

array2string(a[, max_line_width, precision, ...])Return a string representation of an array.
array_repr(arr[, max_line_width, precision, ...])Return the string representation of an array.
array_str(a[, max_line_width, precision, ...])Return a string representation of the data in an array.

Memory mapping files

memmapCreate a memory-map to an array stored in a binary file on disk.

Base-n representations

binary_repr(num[, width])Return the binary representation of the input number as a string.
base_repr(number[, base, padding])Return a string representation of a number in the given base system.

Data sources

DataSource([destpath])A generic data source file (file, http, ftp, ...).

from: http://blog.csdn.net/pipisorry/article/details/39088003

ref: [numpy Input and output]


转载于:https://my.oschina.net/u/3579120/blog/1508414

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值