python numpy格式化打印的实例


Posted in Python onMay 14, 2018

1.问题描述

在使用numpy的时候,我们经常在debug的时候将numpy数组打印下来,但是有的时候数组里面都是小数,数组又比较大,打印下来的时候非常不适合观察。这里主要讲一下如何让numpy打印的结果更加简洁

2.问题解决

这里需要使用numpy的set_printoptions函数,对应numpy源码如下所示:

def set_printoptions(precision=None, threshold=None, edgeitems=None,
      linewidth=None, suppress=None,
      nanstr=None, infstr=None,
      formatter=None):
 """
 Set printing options.
 These options determine the way floating point numbers, arrays and
 other NumPy objects are displayed.
 Parameters
 ----------
 precision : int, optional
  Number of digits of precision for floating point output (default 8).
 threshold : int, optional
  Total number of array elements which trigger summarization
  rather than full repr (default 1000).
 edgeitems : int, optional
  Number of array items in summary at beginning and end of
  each dimension (default 3).
 linewidth : int, optional
  The number of characters per line for the purpose of inserting
  line breaks (default 75).
 suppress : bool, optional
  Whether or not suppress printing of small floating point values
  using scientific notation (default False).
 nanstr : str, optional
  String representation of floating point not-a-number (default nan).
 infstr : str, optional
  String representation of floating point infinity (default inf).
 formatter : dict of callables, optional

这里我们主要用到其中的两个属性:

设置precision来控制小数点后面最多显示的位数

设置suppress来取消使用科学计数法

2.1 简单示例

一个简单的利用set_printoptions的例子如下所示:

import numpy as np
a = np.random.random(3)
print('before set options: \n {}'.format(a))
np.set_printoptions(precision=3, suppress=True)
print('after set options: \n {}'.format(a))
>>>
before set options: 
 [ 0.05856348 0.5417039 0.76520603]
after set options: 
 [ 0.059 0.542 0.765]

可以看到,设置了打印的options之后,打印下来的结果简洁了很多,绝大多数时候我们只需要观察简洁的打印结果,太过精确的结果反而会因为占位太长不易于观察

2.2完整示例

2.1的例子中存在的一个问题是,一旦我们在程序的某一行设置了printoptions之后,接下来所有的打印过程都会受到影响,然而有的时候我们并不希望如此,这个时候我们可以添加一个上下文管理器,只在规定的上下文环境当中设置我们需要的打印参数,其他地方仍然使用默认的打印参数,代码如下:

import numpy as np
from contextlib import contextmanager
@contextmanager
def printoptions(*args, **kwargs):
 original_options = np.get_printoptions()
 np.set_printoptions(*args, **kwargs)
 try:
  yield
 finally:
  np.set_printoptions(**original_options)
x = np.random.random(3)
y = np.array([1.5e-2, 1.5, 1500])
print('-----------before set options-----------')
print('x = {}'.format(x))
print('y = {}'.format(y))
with printoptions(precision=3, suppress=True):
 print('------------set options------------')
 print('x = {}'.format(x))
 print('y = {}'.format(y))
print('---------------set back options-------------')
print('x = {}'.format(x))
print('y = {}'.format(y))
>>>
-----------before set options-----------
x = [ 0.3802371 0.7929781 0.14008782]
y = [ 1.50000000e-02 1.50000000e+00 1.50000000e+03]
------------set options------------
x = [ 0.38 0.793 0.14 ]
y = [ 0.015  1.5 1500. ]
---------------set back options-------------
x = [ 0.3802371 0.7929781 0.14008782]
y = [ 1.50000000e-02 1.50000000e+00 1.50000000e+03]

上面的程序中,我们通过使用contextlib里面的contextmanager为函数set_printoptions设置了上下文,在执行with里面的代码之前,设置打印的参数为precison=3,suppress=True,当跳出with代码块的时候,将打印参数设置为原来默认的打印参数。

这篇python numpy格式化打印的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python中实现延时回调普通函数示例代码
Sep 08 Python
基于numpy.random.randn()与rand()的区别详解
Apr 17 Python
使用python 3实现发送邮件功能
Jun 15 Python
python实现五子棋小游戏
Mar 25 Python
python基于property()函数定义属性
Jan 22 Python
在python中利用dict转json按输入顺序输出内容方式
Feb 27 Python
django-orm F对象的使用 按照两个字段的和,乘积排序实例
May 18 Python
python使用建议与技巧分享(一)
Aug 17 Python
Python pathlib模块使用方法及实例解析
Oct 05 Python
通过实例解析python and和or使用方法
Nov 14 Python
Python爬虫回测股票的实例讲解
Jan 22 Python
python使用XPath解析数据爬取起点小说网数据
Apr 22 Python
Python常见字典内建函数用法示例
May 14 #Python
python:print格式化输出到文件的实例
May 14 #Python
查看django版本的方法分享
May 14 #Python
django 修改server端口号的方法
May 14 #Python
python字符串string的内置方法实例详解
May 14 #Python
python获取文件真实链接的方法,针对于302返回码
May 14 #Python
Python工厂函数用法实例分析
May 14 #Python
You might like
php 分页类 扩展代码
2009/06/11 PHP
利用php做服务器和web前端的界面进行交互
2016/10/31 PHP
PHP计算近1年的所有月份
2017/03/13 PHP
php使用curl获取header检测开启GZip压缩的方法
2018/08/15 PHP
php5.x禁用eval的操作方法
2018/10/19 PHP
PHP crypt()函数的用法讲解
2019/02/15 PHP
javascript英文日期(有时间)选择器
2007/05/02 Javascript
浅析JavaScript中的CSS属性及命名规范
2013/11/28 Javascript
jquery新的绑定事件机制on方法的使用方法
2014/04/15 Javascript
jQuery之Deferred对象详解
2014/09/04 Javascript
采用自执行的匿名函数解决for循环使用闭包的问题
2014/09/11 Javascript
JS回调函数的应用简单实例
2014/09/17 Javascript
JS实现让网页背景图片斜向移动的方法
2015/02/25 Javascript
JavaScript动态修改网页元素内容的方法
2015/03/21 Javascript
jquery.validate使用时遇到的问题
2015/05/25 Javascript
jQuery Dialog对话框事件用法实例分析
2016/05/10 Javascript
jQuery的Cookie封装,与PHP交互的简单实现
2016/10/05 Javascript
vue.js+Element实现表格里的增删改查
2017/01/18 Javascript
在vue中v-bind使用三目运算符绑定class的实例
2018/09/29 Javascript
后台使用freeMarker和前端使用vue的方法及遇到的问题
2019/06/13 Javascript
解决jquery validate 验证不通过后验证正确的信息仍残留在label上的方法
2019/08/27 jQuery
js实现数字滚动特效
2019/12/16 Javascript
js实现数据导出为EXCEL(支持大量数据导出)
2020/03/31 Javascript
[08:54]DOTA2-DPC中国联赛 正赛 Aster vs LBZS 选手采访
2021/03/11 DOTA
Python中List.count()方法的使用教程
2015/05/20 Python
浅谈python迭代器
2017/11/08 Python
python 读取txt中每行数据,并且保存到excel中的实例
2018/04/29 Python
3个用于数据科学的顶级Python库
2018/09/29 Python
Python用61行代码实现图片像素化的示例代码
2018/12/10 Python
Python获取网段内ping通IP的方法
2019/01/31 Python
详解Python3中ceil()函数用法
2019/02/19 Python
如何使用pandas读取txt文件中指定的列(有无标题)
2020/03/05 Python
高三励志标语
2014/06/05 职场文书
师范生求职信
2014/06/14 职场文书
父亲节寄语大全
2015/02/27 职场文书
2016银行招聘自荐信
2016/01/28 职场文书