7

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

istern
  • 363
  • 1
  • 4
  • 13

1 Answers1

6

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  |
+---------------+---------+
TimD
  • 312
  • 3
  • 10
  • 3
    This does not work for me. The table title is not shown. Tested with Python 3.4.3 and following dependencies: tables (3.4.2), prettytable (0.7.2). – istern Sep 29 '17 at 09:20
  • It only works with PTable (see link above, I use version 0.9.2). This is a different package but shares the basic syntax with prettytable since it was originally forked from it. – TimD Sep 29 '17 at 09:37
  • 2
    After adding the PTable dependency (pip install ptable) it does work. Accepting your answer. – istern Oct 01 '17 at 09:43