For those that come here not because wanted to round the DataFrame but merely want to limit the displayed value to n
decimal places, use pd.set_option
instead. This methods will make all printed DataFrame on your notebook follow the option.
import pandas as pd
pd.set_option('precision', 2)
EDIT:
To also suppress scientific notation, use:
pd.set_option('float_format', '{:.2f}'.format)
EDIT 2:
Combining with IPython and pandas option context manager, you can use:
from IPython.display import display
with pd.option_context('precision', 3,
'float_format', '{:.2f}'.format):
display(pd.DataFrame(data={'x':[1,2,3],
'y':[4,5,6]}))
EDIT 3
Latest pandas changes the API on set_option
. I don't know exactly when it is changed, but version 1.5.1 and later use 'display.precision'
instead of 'precision'
:
from IPython.display import display
with pd.option_context('display.precision', 3,
'display.float_format', '{:.2f}'.format):
display(pd.DataFrame(data={'x':[1,2,3],
'y':[4,5,6]}))
BONUS:
For numpy
, use:
np.set_printoptions(precision=2, # limit to two decimal places in printing numpy
suppress=True, # suppress scientific notation in printing numpy
)
Read more at: https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html