Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

python - NumPy: Pretty print tabular data

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', '|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')]

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-05 | ABCD
          2 |   1e-08 | long string
          3 |   1e-07 | ABCD

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...