SoFunction
Updated on 2024-11-15

Two tools for python to beautify the output of tabular data

preamble

In processing tabular data with python, the focus of this work is to sort, calculate and display tabular types of data, this article focuses on displaying this aspect of the work.

First let's look at a case where we define a table of data in the form of an array:

[dechin@dechin-manjaro table]$ ipython
Python 3.8.5 (default, Sep  4 2020, 07:30:14) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: table=[('a',1,2,3),('b',2,3,4)]

In [2]: print(table)
[('a', 1, 2, 3), ('b', 2, 3, 4)]

When we print the data from this form directly, we find that the results are very difficult to see. Although we can get the same information from this form, this method of presenting the data is very unfavorable for us to get the data directly from the printout.

1. Use tabulate to beautify the table output

First introduce a tool tabulate, you can directly print the array format of the table data, and there are a variety of output formats to choose from. Installation method can also be managed with pip:

[dechin@dechin-manjaro table]$ python3 -m pip install tabulate
Requirement already satisfied: tabulate in /home/dechin/anaconda3/lib/python3.8/site-packages (0.8.9)

Installation was easy and there are no other dependencies.

Next we show some basic usage with ipython:

[dechin@dechin-manjaro table]$ ipython
Python 3.8.5 (default, Sep  4 2020, 07:30:14) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from tabulate import tabulate
In [2]: import numpy as np
In [3]: header=['index']+list(range(4)) # Definition of table headers
In [4]: header
Out[4]: ['index', 0, 1, 2, 3]
In [8]: table=[('Alice',1,2,3,4),('Bob',2,3,4,5)] # Definition of table content
In [9]: table
Out[9]: [('Alice', 1, 2, 3, 4), ('Bob', 2, 3, 4, 5)]
In [11]: print(tabulate(table,headers=header,tablefmt='grid')) # Print table contents in grid format
+---------+-----+-----+-----+-----+
| index   |   0 |   1 |   2 |   3 |
+=========+=====+=====+=====+=====+
| Alice   |   1 |   2 |   3 |   4 |
+---------+-----+-----+-----+-----+
| Bob     |   2 |   3 |   4 |   5 |
+---------+-----+-----+-----+-----+

In [12]: print(tabulate(table,headers=header,tablefmt='fancy_grid')) # Printed in fancy_grid format
╒═════════╤═════╤═════╤═════╤═════╕
│ index   │   0 │   1 │   2 │   3 │
╞═════════╪═════╪═════╪═════╪═════╡
│ Alice   │   1 │   2 │   3 │   4 │
├─────────┼─────┼─────┼─────┼─────┤
│ Bob     │   2 │   3 │   4 │   5 │
╘═════════╧═════╧═════╧═════╧═════╛

In this case, we have generated an array of table headers and table contents, and then used tabulate to encapsulate and then print them out. Since tabulate supports a variety of output formats, here we show only grid and fancy_grid two personally preferred formats

Other types of formats are available:

"plain"
"simple"
"github"
"grid"
"fancy_grid"
"pipe"
"orgtbl"
"jira"
"presto"
"psql"
"rst"
"mediawiki"
"moinmoin"
"youtrack"
"html"
"latex"
"latex_raw"
"latex_booktabs"
"textile"

2. Use prettytable to beautify the output

Similar to tabulate, prettytable's main purpose is also to standardize the beautification of the table data output, but in the use of slightly different methods, in different scenarios can be used in different programs.

Here we'll look at the prettytable installation, which again can be managed using pip:

[dechin@dechin-manjaro table]$ python3 -m pip install prettytable
Collecting prettytable
  Downloading prettytable-2.1. (22 kB)
Requirement already satisfied: wcwidth in /home/dechin/anaconda3/lib/python3.8/site-packages (from prettytable) (0.2.5)
Installing collected packages: prettytable
Successfully installed prettytable-2.1.0

After installation we show its usage with an example py file:

from prettytable import PrettyTable
tb = PrettyTable() # Generate form objects
tb.field_names = ['Index', 0, 1, 2, 3] # Define table headers
tb.add_row(['Alice',1,2,3,4]) # Add a row with column
tb.add_row(['Bob',2,3,4,5])
print (tb) # printout

The execution result of the code is as follows:

[dechin@dechin-manjaro table]$ python3 pt_test.py 
+-------+---+---+---+---+
| Index | 0 | 1 | 2 | 3 |
+-------+---+---+---+---+
| Alice | 1 | 2 | 3 | 4 |
|  Bob  | 2 | 3 | 4 | 5 |
+-------+---+---+---+---+

As the use of the case with the tabulate introduced above is the same, so the output results are similar, equivalent to more than one output format. But in addition to the output format, we found that prettytable can be very good use of rows and columns of the form of adding to the table operation, the operation of the habit is closer to the form of database operations, so for frequent use of the database, prettytable may be a better solution to the output of tabular data.

summarize

This article describes the two table data printing tools: tabulate and prettytable installation and basic usage. As the tabular data itself is not standardized on the output format, so the printed data will appear more messy, not conducive to intuitive reading. Therefore the introduction of these two tools to enhance the readability of the output results. Both have their advantages and disadvantages in use, tabulate supports more forms of table styles, while prettytable uses a form of operation closer to the database, for some users have a natural ecological advantage.

to this article on python can beautify the table data output results of the two tools are introduced to this article, more related python beautify the table output content please search my previous posts or continue to browse the following related articles I hope that you will support me more in the future!