Mik*_*e T 14 python numpy pretty-print tabular
我想打印NumPy表格数组数据,以便它看起来不错.R和数据库控制台似乎表现出很好的能力.但是,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')])
Run Code Online (Sandbox Code Playgroud)
我希望看起来更像数据库吐出的东西,例如postgres风格:
column_one | col_two | column_3
------------+---------+-------------
0 | 0.0001 | ABCD
1 | 1e-005 | long string
2 | 1e-008 | ABCD
3 | 1e-007 | ABCD
Run Code Online (Sandbox Code Playgroud)
是否有任何好的第三方Python库来格式化漂亮的ASCII表?
我使用的是Python 2.5,NumPy 1.3.0.
Mik*_*e T 21
我似乎有很好的输出和漂亮:
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'
Run Code Online (Sandbox Code Playgroud)
而且输出也不错.在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
Run Code Online (Sandbox Code Playgroud)
该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)
Run Code Online (Sandbox Code Playgroud)
(上面的代码是Python 3;对于Python 2,from __future__ import print_function
在脚本顶部添加)
输出:
???????????????????????????????
? col 1 ? col 2 ? col 3 ?
???????????????????????????????
? 1 ? 2 ? 3 ?
???????????????????????????????
? 4 ? 5 ? 6 ?
???????????????????????????????
Run Code Online (Sandbox Code Playgroud)
该软件包通过pip
以下方式安装
$ pip install tabulate # (use pip3 for Python 3 on some systems)
Run Code Online (Sandbox Code Playgroud)
你可以利用数组理解并使用printf格式字符串:
for c1, c2, c3 in dat:
print "%2f | %8e | %s" % (c1, c2, c3)
Run Code Online (Sandbox Code Playgroud)
https://en.wikipedia.org/wiki/Printf_format_string
如果你达到2.7版本,你可以获得更多自定义
您可能想要查看Pandas,它有很多很好的功能来处理表格数据,并且似乎在打印时更好地处理(它被设计为R的python替代品):
归档时间: |
|
查看次数: |
31401 次 |
最近记录: |