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数组打印效果设置

np.set_printoptions(precision=5, suppress=True, formatter={'float': '{: 0.3f}'.format}, linewidth=120)

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

如果一个数组用来打印太大了,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).

“大”矩阵输出

“大”矩阵输出时,Pycharm console自动添加换行符

PyCharm默认控制台宽度设置为80个字符。


np.set_printoptions(linewidth=120)

对于pandas:
pd.set_option('display.width', 120)

使用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)yieldnp.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保存list或者ndarray

np.savetxt('nationwide_add.csv', add_list, fmt='%s', encoding='utf-8', delimiter='\t')

可以保存中文,但是其中的None也变成了字符串“None”而不是真的空。所以建议使用pd.DataFrame(add_list).to_csv('nationwide_add.csv', sep='\t', header=False, index=False)。

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

memmap Create 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:numpy教程:基本输入输出和文件输入输出Input and output_皮皮blog-CSDN博客

ref: [numpy Input and output]

numpy教程:基本输入输出和文件输入输出Input and output相关推荐

  1. Angular4学习笔记(六)- Input和Output

    概述 Angular中的输入输出是通过注解@Input和@Output来标识,它位于组件控制器的属性上方. 输入输出针对的对象是父子组件. 演示 Input 新建项目connInComponents: ...

  2. angular input和output

    Angular中的输入输出是通过注解@Input和@Output来标识,它位于组件控制器的属性上方. 输入输出针对的对象是父子组件. @Input和@Output这两个要结合父组件与子组件来说 @In ...

  3. python 学习笔记 5 -- 文件输入输出

    本文主要介绍python下的文件输入输出操作,python的文件操作简单易用-通过本文相信你可以熟练掌握file和pickle这两种输入输出操作! 1.文件 你可以通过创建一个file类的对象来打开一 ...

  4. python 中文件输入输出及os模块对文件系统的操作

    整理了一下python 中文件的输入输出及主要介绍一些os模块中对文件系统的操作. 文件输入输出 1.内建函数open(file_name,文件打开模式,通用换行符支持),打开文件返回文件对象. 2. ...

  5. 标准库 - 输入输出处理(input and output facilities) lua

    标准库 - 输入输出处理(input and output facilities) 责任编辑:cynthia作者:来自ITPUB论坛 2008-02-18 文本Tag: Lua [IT168 技术文档 ...

  6. C++primer第八章 IO库 8.2 文件输入输出

    8.2文件输入输出 头文件fstream定义了三个类型来支持文件IO:ifstream从一个给定文件读取数据,ofstream向一个给定文件写入数据,以及fstream可以读写给定文件.在17.5.3 ...

  7. C ++基础 | 格式化输出,文件输入输出(File IO),头文件(Header Files)_3

    目录 格式化输出 文件输入输出(File IO) 头文件(Header Files) 格式化输出 要格式化数据,我们可以使用转义字符串(Escape Sequence)也称字符实体(Character ...

  8. 5. Linux C 输入输出与文件

    LINUX输入输出与文件 1.基于文件指针的文件操作(缓冲) 先来介绍 6 个概念: ① linux的文件和文件描述符 linux中对目录和设备的操作都是文件操作,文件分为普通文件,目录文件,链接文件 ...

  9. 【C++】IO库 : IO类,文件输入输出,string流

    前面已经在用的IO库设施 istream:输入流类型,提供输入操作. ostream:输出流类型,提供输出操作 cin:一个istream对象,从标准输入读取数据. cout:一个ostream对象, ...

  10. 分治法求众数和重数(含文件输入输出)

    [mie haha的博客]转载请注明出处(万分感谢!): https://blog.csdn.net/qq_40315080/article/details/88580999 (可以列出所有众数) 代 ...

最新文章

  1. Nat. Commun | 基于网络的药物组合预测
  2. Robot Cleaner I
  3. python语言的重要性_【一点资讯】这个可能打败Python的编程语言,正在征服科学界 www.yidianzixun.com...
  4. .NET Core采用的全新配置系统[5]: 聊聊默认支持的各种配置源[内存变量,环境变量和命令行参数]...
  5. 【论文笔记】Beyond Low-frequency Information in Graph Convolutional Networks
  6. css补充、JavaScript、Dom
  7. Visual Studio 2017各版本离线安装包获取以及安装教程
  8. python怎么用pandas查找指定字符串_Python Pandas:通过搜索子字符串查找表
  9. 分享微信预约系统开发制作步骤_教你实现微信公众预约系统的方法
  10. “今夜酒店特价”的商业模式是什么?
  11. 一文搞懂R(相关系数)与R^2(决定系数)
  12. PLC通讯实现-C#访问OpcUa实现读写PLC(十)
  13. ARCGIS中坐标转换及地理坐标、投影坐标的定义
  14. 聚观早报 | 特斯拉上线Steam平台;苹果CEO库克访问索尼
  15. Android - 屏幕适配
  16. kafka文档: 配置选项翻译
  17. 前端开发调试之代理配置
  18. 介绍国内外CMS系统
  19. 用Look'n'Stop防火墙实现ARP终极防御
  20. solar2 android,solarwalk2

热门文章

  1. Flask-SQLALchemy查询
  2. 推荐两个不错的前端资源的网站,有好的请继续添加,谢谢!
  3. 线程挂起 阻止有什么区别c#
  4. JAVA JDK 、Maven、IDEA安装
  5. 移动端动画使用transform提升性能
  6. 在一个环境中使用不同版本的rails
  7. 今天迈出第一步,开始了解iphone开发
  8. Got error ‘parentheses not balanced‘ from regexp
  9. 如何系统地学习深度学习(从初级到高级,初学者必看)
  10. 每日算法系列【LeetCode 309】最佳买卖股票时机含冷冻期