NumPy:漂亮的打印表格数据 [英] NumPy: Pretty print tabular data

查看:307
本文介绍了NumPy:漂亮的打印表格数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印NumPy表格数组数据,以使其看起来不错. R和数据库控制台似乎表现出了很好的能力.但是,NumPy内置的表格数组打印看起来像垃圾:

I would like to print NumPy tabular array data, so that it looks nice. R and database consoles seem to demonstrate good abilities to do this. However, NumPy's built-in printing of tabular arrays looks like garbage:

import numpy as np
dat_dtype = {
    'names' : ('column_one', 'col_two', 'column_3'),
    'formats' : ('i', 'd', '|S12')}
dat = np.zeros(4, dat_dtype)
dat['column_one'] = range(4)
dat['col_two'] = 10**(-np.arange(4, dtype='d') - 4)
dat['column_3'] = 'ABCD'
dat['column_3'][2] = 'long string'

print(dat)
# [(0, 0.0001, 'ABCD') (1, 1.0000000000000001e-005, 'ABCD')
#  (2, 9.9999999999999995e-007, 'long string')
#  (3, 9.9999999999999995e-008, 'ABCD')]

print(repr(dat))
# array([(0, 0.0001, 'ABCD'), (1, 1.0000000000000001e-005, 'ABCD'),
#        (2, 9.9999999999999995e-007, 'long string'),
#        (3, 9.9999999999999995e-008, 'ABCD')], 
#       dtype=[('column_one', '<i4'), ('col_two', '<f8'), ('column_3', '|S12')])

我想要看起来更像数据库的东西,例如postgres风格:

I would like something that looks more like what a database spits out, for example, postgres-style:

 column_one | col_two |  column_3
------------+---------+-------------
          0 |  0.0001 | ABCD
          1 |  1e-005 | long string
          2 |  1e-008 | ABCD
          3 |  1e-007 | ABCD

有没有好的第三方Python库来格式化美观的ASCII表?

Are there any good third-party Python libraries to format nice looking ASCII tables?

我正在使用Python 2.5,NumPy 1.3.0.

I'm using Python 2.5, NumPy 1.3.0.

推荐答案

我似乎在漂亮表上表现不错>:

I seem to be having good output with prettytable:

from prettytable import PrettyTable
x = PrettyTable(dat.dtype.names)
for row in dat:
    x.add_row(row)
# Change some column alignments; default was 'c'
x.align['column_one'] = 'r'
x.align['col_two'] = 'r'
x.align['column_3'] = 'l'

而且输出还不错.甚至还有一个border开关,以及其他一些选项:

And the output is not bad. There is even a border switch, among a few other options:

>>> print(x)
+------------+---------+-------------+
| column_one | col_two |   column_3  |
+------------+---------+-------------+
|          0 |  0.0001 | ABCD        |
|          1 |  1e-005 | ABCD        |
|          2 |  1e-006 | long string |
|          3 |  1e-007 | ABCD        |
+------------+---------+-------------+
>>> print(x.get_string(border=False))
 column_one  col_two    column_3  
          0   0.0001  ABCD        
          1   1e-005  ABCD        
          2   1e-006  long string 
          3   1e-007  ABCD        

这篇关于NumPy:漂亮的打印表格数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆