szczor1
szczor1

Reputation: 191

How can I add column to prettytable as a first column

I have some table x which I have done with prettytable module. Now I want to add a column to it, but I want it to be added as a first column, how can I do that?

Method add_column puts my column on the last spot.

Upvotes: 1

Views: 4277

Answers (1)

Hami
Hami

Reputation: 714

From reading the documentation there are two ways. You can simply regenerate the table from scratch, making sure you add the column in question first.

The second possibility is to access the data structures making up the PrettyTable and modifying them manually. Beware that any mistake made this way will not be caught by the validation build around the default add_column function.

If we have a table

from prettytable import PrettyTable

x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x)

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
|   Perth   | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

To insert a column at the beginning

fieldname = 'Number'
x._field_names.insert(0, fieldname) 
x._align[fieldname] = 'c' 
x._valign[fieldname] = 't' 
for i, _ in enumerate(x._rows): 
    x._rows[i].insert(0, i) 

print(x)

+--------+-----------+------+------------+-----------------+
| Number | City name | Area | Population | Annual Rainfall |
+--------+-----------+------+------------+-----------------+
|   0    |  Adelaide | 1295 |  1158259   |      600.5      |
|   1    |  Brisbane | 5905 |  1857594   |      1146.4     |
|   2    |   Darwin  | 112  |   120900   |      1714.7     |
|   3    |   Hobart  | 1357 |   205556   |      619.5      |
|   4    |   Sydney  | 2058 |  4336374   |      1214.8     |
|   5    | Melbourne | 1566 |  3806092   |      646.9      |
|   6    |   Perth   | 5386 |  1554769   |      869.4      |
+--------+-----------+------+------------+-----------------+

Now you can use my example on how I added the field Number to add a field of your choice.

I would still highly recommend you process the data before creating the table and only then dealing with PrettyTable.

Upvotes: 3

Related Questions