4

I have a pandas dataframe column that I would like to be formatted to two decimal places.

Such that:

10.1

Appears as:

10.10

How can I do that? I have already tried rounding.

David
  • 53
  • 2
  • 6
  • Does this answer your question? [Add zeros to a float after the decimal point in Python](https://stackoverflow.com/questions/15619096/add-zeros-to-a-float-after-the-decimal-point-in-python) – iacob Sep 30 '21 at 23:26

4 Answers4

3

This can be accomplished by mapping a string format object to the column of floats:

df.colName.map('{:.2f}'.format)

(Credit to exp1orer)

johnDanger
  • 1,990
  • 16
  • 22
1

You can use:

pd.options.display.float_format = '{:,.2f}'.format

Note that this will only display two decimals for every float in your dataframes.
To go back to normal:

pd.reset_option('display.float_format')
Horace
  • 1,024
  • 7
  • 12
0

From pyformat.info

Padding numbers

For floating points the padding value represents the length of the complete output. In the example below we want our output to have at least 6 characters with 2 after the decimal point.

'{:06.2f}'.format(3.141592653589793)

The :06 is the length of your output regardless of how many digits are in your input. The .2 indicates you want 2 places after the decimal point. The f indicates you want a float output.

Output

003.14
APhillips
  • 1,175
  • 9
  • 17
-2

If you are using Python 3.6 or later you can use f strings. Check out this other answer: https://stackoverflow.com/a/45310389/12229158

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
whege
  • 1,391
  • 1
  • 5
  • 13
  • 1
    How do you do this for a whole column? – David Nov 19 '19 at 16:37
  • I think the most straightforward way is a list comprehensions, as suggested on another thread. This would be: df['b'] = [f'{a:.2f}' for a in df['column']]. This creates a new column but you could swap 'b' for the column of interest to overwrite, or drop the old column after creating this new one. – whege Nov 19 '19 at 16:57