How to use tabulate to format number with thousand separator and right align

13k Views Asked by At

I am using tabulate (https://pypi.org/project/tabulate/) and I want to format a number column with thousand separator and right align it. This is what I have done and it doesn't right align my column.

import pandas as pd
rom tabulate import tabulate

df = pd.DataFrame([{'size':225612466, 'path': '/etc'}, {'size':66, 'path': '/home'}])
df['size'] = df['size'].apply(lambda x: "{:,}".format(x).rjust(15))
print(tabulate(df, headers='keys', tablefmt='psql', showindex=False))

+--------+-------------+
| path   | size        |
|--------+-------------|
| /etc   | 225,612,466 |
| /home  | 66          |
+--------+-------------+

I would like it to be like this:

+--------+-----------------+
| path   | size            |
|--------+-----------------|
| /etc   |     225,612,466 |
| /home  |              66 |
+--------+-----------------+

Thanks,

3

There are 3 best solutions below

5
On

I guess the missing parameter in tabulate is numalign="right" but you have to get rid of manual rjust which changes the values to str:

import pandas as pd
rom tabulate import tabulate

df = pd.DataFrame([{'size':225612466, 'path': '/etc'}, {'size':66, 'path': '/home'}])
print(tabulate(df, headers='keys', tablefmt='psql', showindex=False, numalign="right"))

Gives output:

+--------+-----------+
| path   |      size |
|--------+-----------|
| /etc   | 225612466 |
| /home  |        66 |
+--------+-----------+

If you want to keep the thousands separators you have to keep the formatting and align strings to the rigth using stralign:

print(tabulate(df, headers='keys', tablefmt='psql', showindex=False, stralign="right"))
0
On

Usage of tabulate

tabulate(
    tabular_data, 
    headers, tablefmt, 
    floatfmt, 
    numalign,  # ---> here
    stralign, 
    missingval, 
    showindex, 
    disable_numparse, 
    colalign, 
    maxcolwidths
)

So that, to make number align left you can use numalign="left"

0
On

The numbers have all become strings. Add the option: colalign("right", "left"). Let's test the suggestion...

print(tabulate(df, headers='keys', tablefmt='psql', showindex=False, colalign=("right", "left")))
+-------------+--------+
|        size | path   |
|-------------+--------|
| 225,612,466 | /etc   |
|          66 | /home  |
+-------------+--------+

Bingo, bingo. It is in their docs.