漂亮的打印和替代numpy数组

时间:2015-01-13 19:21:08

标签: python json numpy pretty-print

想象一下,我正在打印一个具有以下结构的JSON解码对象:

{Stack
   Layer
     Material
       <array>
}

这些变量对应于模拟中的结构层次结构。在层次结构的末尾,有一个numpy数组对象。这些数组往往非常大,所以我不打算明确地打印它们,而是打印摘要。所以而不是:

{Stack
   Layer
     Material
       array([1,2,3,4,5......])
}

看起来像是:

{Stack
   Layer
     Material
       array: dtype, shape
}

IE漂亮的打印不会打印整个数组,只是通过打印形状和数据类型来总结它的信息。在prettyprint中可以使用这种自定义吗?

2 个答案:

答案 0 :(得分:1)

好的,我是一名分子生物学家而不是专业程序员,所以请耐心等待 在我非常天真的意见中,你不应该考虑太多,其中一个选择是制作你自己的pprint版本,知道numpy的{​​{1}}个对象,并按照它们的方式打印它们你想要他们。

我所做的和它一起工作的是打开ndarray模块(在pprint目录下)并创建一个修改过的副本,如下所示:

(我在pastebin上粘贴了经过修改的工作代码,你可以找到它here

首先,在导入部分中,让它尝试导入numpy的Lib,添加:

ndarray

然后,在try: from numpy import ndarray np_arrays = True except ImportError: np_arrays = False 函数的定义中,右之后

_format

(所以在我的副本第154行,在导入之后)你应该添加:

# This is already there
if self._depth and level > self._depth:
    write(rep)
    return

(然后函数继续,# Format numpy.ndarray object representations if np_arrays and issubclass(typ, ndarray): write('array(dtype:' + str(object.dtype)) write('; shape: ' + str(object.shape) + ')') return ...)

现在将此脚本保存在pprint所在的同一个Lib目录中,使用新名称r = getattr(typ, "__repr__", None),然后尝试:

mypprint.py

答案 1 :(得分:0)

你还在监听这个问题吗? 我一直在思考,如果你想让它更具可移植性,你可以保持pprint模块不变,只需在脚本中为_format方法添加一个装饰器,即:

import pprint
import numpy as np

def ndarray_catch(original_format_func):
    def _format(*argv):
        myobj = argv[1]
        if issubclass(type(myobj), np.ndarray):
            array_text = 'array(dtype:' + str(myobj.dtype)
            array_text +='; shape:' + str(myobj.shape) + ')'
            argv = list(argv)
            argv[1] = array_text
        return original_format_func(*argv)
    return _format

pprint.PrettyPrinter._format = ndarray_catch(pprint.PrettyPrinter._format)

尝试使用:

my_list = [1, 2, {3:4, 5:"I like to import antigravity"}, \
           ["this is a very very long text", "smalltext", 
            np.array([[7,8], [9, 10]])], ("here", "there", ["everywhere"])]    
pprint.pprint(my_list)

输出结果为:

[1,
 2,
 {3: 4, 5: 'I like to import antigravity'},
 ['this is a very very long text',
  'smalltext',
  'array(dtype:int32; shape:(2L, 2L))'],
 ('here', 'there', ['everywhere'])]