pythonprettytable

Python PrettyTable: Add title above the table's header


I have a script which generates multiple tables, which all have the same column names and very similar data. Until now I've been making each table unique by printing a title before it, i.e.:

print("Results for Method Foo")
#table 1
print("Results for Method Bar")
#table 2 

and so on. But that's not really pretty..

Although it seems like an obvious use case, I couldn't find anywhere the option to do something like this:

PrettyTable with title

Any ideas about how I could achieve this?

Just in case it matters: I'm using python 3.4 with, with a virtualenv and prettytable version 0.7.2


Solution

  • This can be achieved using the PTable library, which is originally forked from PrettyTable. I did not find this in the documentation, so it might be useful for others that the syntax is simply as follows:

    from prettytable import PrettyTable
    
    table = PrettyTable()
    
    table.title = 'Results for method Foo'
    table.field_names = ['Experiment', 'Value']
    table.add_row(['bla', 3.14])
    table.add_row(['baz', 42.0])
    
    print(table)
    

    This gives the desired output:

    +-------------------------+
    |  Results for method Foo |
    +---------------+---------+
    |   Experiment  |  Value  |
    +---------------+---------+
    |      bla      |   3.14  |
    |      baz      |   42.0  |
    +---------------+---------+