Python NumPy:漂亮的打印表格数据

Python NumPy:漂亮的打印表格数据,python,numpy,pretty-print,tabular,Python,Numpy,Pretty Print,Tabular,我想打印NumPy表格数组数据,这样看起来就不错了。R和数据库控制台似乎展示了很好的能力。但是,NumPy内置的表格数组打印看起来像垃圾: import numpy as np dat_dtype = { 'names' : ('column_one', 'col_two', 'column_3'), 'formats' : ('i', 'd', '|U12')} dat = np.zeros(4, dat_dtype) dat['column_one'] = range(4)

我想打印NumPy表格数组数据,这样看起来就不错了。R和数据库控制台似乎展示了很好的能力。但是,NumPy内置的表格数组打印看起来像垃圾:

import numpy as np
dat_dtype = {
    'names' : ('column_one', 'col_two', 'column_3'),
    'formats' : ('i', 'd', '|U12')}
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, 1.e-04, 'ABCD') (1, 1.e-05, 'ABCD') (2, 1.e-06, 'long string')
#  (3, 1.e-07, 'ABCD')]
我想要看起来更像数据库的东西,例如postgres样式:

 column_one | col_two |  column_3
------------+---------+-------------
          0 |  0.0001 | ABCD
          1 |   1e-05 | ABCD
          2 |   1e-08 | long string
          3 |   1e-07 | ABCD

有没有什么好的第三方Python库可以格式化漂亮的ASCII表?

您可能想看看Pandas,它有很多处理表格数据的好功能,并且在打印时似乎布局得更好(它被设计成Python来替代ASCII表):


您可以利用数组理解并使用printf格式字符串:

for c1, c2, c3 in dat:  
    print "%2f | %8e | %s" % (c1, c2, c3)


如果升级到2.7版,您还可以进行更多定制。我似乎在以下方面获得了良好的输出:

而且输出也不错。在其他几个选项中,甚至还有一个
边框
开关:

>>> print(x)
+------------+---------+-------------+
| column_one | col_two | column_3    |
+------------+---------+-------------+
|          0 |  0.0001 | ABCD        |
|          1 |   1e-05 | ABCD        |
|          2 |   1e-06 | long string |
|          3 |   1e-07 | ABCD        |
+------------+---------+-------------+
>>> print(x.get_string(border=False))
 column_one  col_two  column_3  
          0   0.0001  ABCD        
          1    1e-05  ABCD        
          2    1e-06  long string 
          3    1e-07  ABCD        
该软件包适用于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)
(上面的代码是Python3;对于Python2,在脚本顶部添加来自_future _导入print_函数的

输出:

╒═════════╤═════════╤═════════╕
│   col 1 │   col 2 │   col 3 │
╞═════════╪═════════╪═════════╡
│       1 │       2 │       3 │
├─────────┼─────────┼─────────┤
│       4 │       5 │       6 │
╘═════════╧═════════╧═════════╛
软件包通过
pip
安装:

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

这个问题可能会有所帮助。您和其他通过谷歌搜索来到这里的人可能也很感兴趣。只是想添加一条评论,截至2013年4月7日,
prettytable
现在是PyPI的一部分:。因此,您可以使用
pip
easy\u install
立即安装,而不是通过谷歌代码下载。顺便说一句,谢谢你的提示+1.最简单、最好的解决方案
$ pip install tabulate     # (use pip3 for Python 3 on some systems)