Select to view content in your preferred language

Pandas Styler format justify prefix left value right (e.g. $ accounting format)

1217
1
Jump to solution
11-19-2023 07:35 AM
TylerT
by
Frequent Contributor

Hello,

I am using the Pandas Styler style.format() method to deal with a currency column.  Sample code and format is :

import pandas as pd

df = pd.DataFrame({'quantity':[2, 45, 322],
                   'unit_cost': [1005.00, 1.92, 0.50]})
df['cost'] = df['quantity'].multiply(df['unit_cost'])

formats = (
        {
           'quantity': "{:,.0f}".format,
           'unit_cost': "$ {:,.2f}".format,
           'cost': "$ {:,.2f}".format,
        }
    )

dfs = df.style.format(formats)

And the resulting styled dataframe is:

TylerT_0-1700407875545.png

However, I'm looking for more of an accounting look where the $ (dollar sign) is justified and aligned left such as this:

TylerT_1-1700408006864.png

Any suggestions on how to write the format to achieve this would be appreciated.  Thank you.

Tyler

0 Kudos
1 Solution

Accepted Solutions
DanPatterson
MVP Esteemed Contributor
0 Kudos
1 Reply
DanPatterson
MVP Esteemed Contributor
0 Kudos