2012-03-14 117 views
13

我想打印NumPy表格数组数据,以便它看起来不错。 R和数据库控制台似乎表现出很好的能力来做到这一点。然而,NumPy的内置的表格列的打印看起来像垃圾:NumPy:漂亮的打印表格数据

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的风格:

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表?

我使用Python 2.5,NumPy 1.3.0。

+0

这个问题[Python的:漂亮印刷ASCII表(http://stackoverflow.com/q/5909873/404469)可以帮助。 – gary 2012-03-15 01:39:55

回答

19

stomized我似乎有与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开关,其他几个选项中选择:

>>> 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   
+0

只想在2013年4月7日添加一个评论,指出'prettytable'现在是PyPI的一部分:https://pypi.python.org/pypi/PrettyTable。因此,您可以使用'pip'或'easy_install'来安装它,而不是通过Google Code下载。顺便说一句,谢谢你的提示。 +1。 – rayryeng 2017-03-13 14:22:02

5

你可能想看看熊猫里面有很多不错的功能来处理表格数据,似乎在打印时最好一五一十的事情了(它的设计是一个Python替代R):

http://pandas.pydata.org/

0

tabulate包很好地工作为numpy的数组:

import numpy as np 
from tabulate import tabulate 

m = np.array([[1, 2, 3], [4, 5, 6]]) 
headers = ["col 1", "col 2", "col 3"] 

# tabulate data 
table = tabulate(m, headers, tablefmt="fancy_grid") 

# output 
print(table) 

(上面的代码的Python 3;用于Python 2在顶部添加from __future__ import print_function脚本)

输出:

╒═════════╤═════════╤═════════╕ 
│ col 1 │ col 2 │ col 3 │ 
╞═════════╪═════════╪═════════╡ 
│  1 │  2 │  3 │ 
├─────────┼─────────┼─────────┤ 
│  4 │  5 │  6 │ 
╘═════════╧═════════╧═════════╛ 

封装经由pip安装:

$ pip install tabulate  # (use pip3 for Python 3 on some systems)