NumPy:漂亮地打印表格数据

20

我想打印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')]

我希望得到类似数据库输出的格式,比如像PostgreSQL风格:

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


这个问题 Python:漂亮打印ASCII表格? 可能会有所帮助。 - gary
这个讨论可能对通过谷歌搜索到达此处的您和其他人也很有趣。 - Foad S. Farimani
4个回答

26

我似乎在使用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-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        

1
只是想添加一条评论,即“prettytable”现在已经成为PyPI的一部分,截至2013年4月7日:https://pypi.python.org/pypi/PrettyTable。因此,您现在可以使用`pip`或`easy_install`来安装它,而不是通过Google Code下载它。顺便说一句,感谢您在这里的提示。+1。 - rayryeng

17

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"]

# Generate the table in fancy format.
table = tabulate(m, headers, tablefmt="fancy_grid")

# Show it.
print(table)

输出:

╒═════════╤═════════╤═════════╕
│   col 1 │   col 2 │   col 3 │
╞═════════╪═════════╪═════════╡
│       1 │       2 │       3 │
├─────────┼─────────┼─────────┤
│       4 │       5 │       6 │
╘═════════╧═════════╧═════════╛
可以通过 PyPI 安装软件包,例如:
$ pip install tabulate

7

6
你可能想看看Pandas,它有很多对处理表格数据非常有用的特性,并且在打印时似乎布局更好(它被设计成Python中替代R的工具):

http://pandas.pydata.org/


最简单且最佳的解决方案 - Toufik ID

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接