2

I am trying to apply a style.format function to a data frame in order to adjust the number of decimal places, since the round() function does not apply. (I don't understand why.)

The data in the df are of the format 123.0, 432.0, and 543.0, but I need them to have two decimal places (e.g., 123.00).

I have verified with the function df.dtypes that the column is of type float.

I tried to apply the following:

import pandas.io.formats.style
import pandas as pd

df['DD'] = df[['Quantity']].style.format("{:.2%}")
df

But the following appears in the DD field:

<pandas.io.formats.style.Styler object at 0x7f...

capture data return

The round() function does not work on the column either.

What can be done?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Gonza
  • 155
  • 2
  • 10
  • Hi @Gonza - I deleted my previous answer because you've changed the question significantly since I first answered. Can you tell us what your python setup is (version #, distribution, juypyterlab/ipython console/python console, etc)? And also, can you explain why you want to round the data? Are you just trying to get the data to display correctly in the python notebook/prompt? Or are you trying to write the data to a file and want the 2-decimal precision to be reflected there? If so, can you post that code? – Michael Delgado Jun 03 '20 at 16:28

1 Answers1

3

The .style gives back a Styler object (reference). The Styler object can be formatted in different ways. This has not happened in your DD column; you are only halfway through.

You can format the dataframe with

df.style.format({'Quantity': "{:.2%}"})

as explained in this SO post.

above_c_level
  • 3,579
  • 3
  • 22
  • 37