Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas Formatting with Currency sign, custom thousand separator and custom decimal separator

My data contain a bunch of floats, which I’d like to format as follows:

  1. Thousand separator is a dot
  2. Decimal separator is comma
  3. Always show two decimals
  4. add Euro sign

This is what I got so far:

import pandas as pd

df = pd.DataFrame({'x': [1.50, 
                    2.3456,
                    10000.22,
                    100.3,
                    6800]})

df['x'].map('{:.2f} €'.format)

This yields

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

0        1.50 €
1        2.35 €
2    10000.22 €
3      100.30 €
4     6800.00 €
Name: x, dtype: object

Desired outcome is however:

0        1,50 €
1        2,35 €
2   10.000,22 €
3      100,30 €
4    6.800,00 €
Name: x, dtype: object

How can this be done?

>Solution :

#                      _ HERE
In [113]: df["x"].map("{:_.2f} €".format).str.translate(str.maketrans("_.", ".,"))
Out[113]:
0         1,50 €
1         2,35 €
2    10.000,22 €
3       100,30 €
4     6.800,00 €
Name: x, dtype: object

python’s formatter accepts a thousand separator but it could be either , or _. Now, you eventually want . but can’t directly do that. And you want , as the decimal separator, so that’s dangerous too. So we use _ as the separator there, only to be replaced later with .. Other replacement we do is . to , in the decimal part

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading