BobJoe1803
BobJoe1803

Reputation: 69

Python table with multiple header lines

I need to create a table to display multiple sets of data that was collected with different conditions. This is what I need the table to look like:

        Config 1        Config 2
Test    Data 1  Data 2  Data 1  Data 2
abc     123     123     123     123

So the system was setup with configuration 1 and then two sets of data were collected. The system is reset with configuration 2 and then the same to sets of data are collected.

I have been trying to use prettytable but haven't found anything that specifies how to make a second header that applies to multiple of the following columns.

Upvotes: 1

Views: 4697

Answers (1)

Martin Evans
Martin Evans

Reputation: 46759

You could write a function to align all of your data entries using the maximum column widths as follows:

def write_cols(data):
    col_spacer = "   "      # added between columns
    widths = [0] * len(data[0])

    # Calculate the widest entry for each column
    for row in data:
        widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)]

    return [col_spacer.join("{:<{width}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data]

data = [['', 'Config 1', '', 'Config 2', ''], ["Test", "Data 1", "Data 2", "Data 1", "Data 2"], ["abc", "123", "123", "123", "123"]]

for row in write_cols(data):
    print row

This would display your data as follows:

       Config 1            Config 2         
Test   Data 1     Data 2   Data 1     Data 2
abc    123        123      123        123

Upvotes: 2

Related Questions