python numpy格式化打印的实例

yipeiwu_com6年前Python基础

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中Django框架下的staticfiles使用简介

django1.3新加入了一个静态资源管理的app,django.contrib.staticfiles。在以往的django版本中,静态资源的管理一向都是个问题。部分app发布的时候会...

python之模拟鼠标键盘动作具体实现

上个月就打算开发个还算好玩的项目,但是一直没时间。这篇是此项目用到的一部分, 处理好此部分基本还差通信等方面的了。首先模拟鼠标键盘按下释放的动作,本人利用X11 这个库,所以要了解X11...

python远程邮件控制电脑升级版

由于前边Python3.4实现远程控制电脑开关机写的远程操控电脑,使用的POP登陆有使用频率限制,导致非常被动,有时候邮件无法读取,下面改用POST网易邮箱的方法,获取邮件 impo...

Python的Tornado框架的异步任务与AsyncHTTPClient

高性能服务器Tornado Python的web框架名目繁多,各有千秋。正如光荣属于希腊,伟大属于罗马。Python的优雅结合WSGI的设计,让web框架接口实现千秋一统。WSGI 把应...

用map函数来完成Python并行任务的简单示例

用map函数来完成Python并行任务的简单示例

众所周知,Python的并行处理能力很不理想。我认为如果不考虑线程和GIL的标准参数(它们大多是合法的),其原因不是因为技术不到位,而是我们的使用方法不恰当。大多数关于Python线程和...