Tristan Forward
Tristan Forward

Reputation: 3524

Round each number in a Python pandas data frame by 2 decimals

This works p_table.apply(pd.Series.round) however it has no decimal places

Documentation says

import pandas as pd

Series.round(decimals=0, out=None)

i tried this p_table.apply(pd.Series.round(2)) but get this error:

unbound method round() must be called with Series instance as first argument (got int instance instead)

How do I round all elements in the data frame to two decimal places?

Upvotes: 40

Views: 148043

Answers (6)

Muhammad Yasirroni
Muhammad Yasirroni

Reputation: 2167

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]}))

EDIT 4:

If your dataframe is Styler object, use pd.set_option('styler.format.precision', 2) instead. See my original answer from other question here

import numpy as np
import pandas as pd
from IPython.display import display


pd.set_option('styler.format.precision', 2)

df = pd.DataFrame(
    np.random.random(size=(2, 3))
)
display(df.style.set_caption("Styler precision"))

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

Upvotes: 5

ewalel
ewalel

Reputation: 2096

Below is a sample reproducible possible way of doing it using pandas round function.

# importing pandas as pd 
import pandas as pd 


# generate sample  dataframe  
df = pd.DataFrame(np.random.random([5, 4]), columns =["A", "B", "C"]) 

# use pandas dataframe.round()function to round off all the decimal values to 2 decimal

df.round(2) 

# If you want to customize the round off by individual columns 
df.round({"A":1, "B":2, "C":3}) 

Upvotes: 16

The_Scan_Master
The_Scan_Master

Reputation: 146

        A       B    C
0       t       8    10.958904
1       w       2    98.630137

To round column C you can use this:

df['c']=df['c'].apply(lambda x:round(x,2))

The output will be:

        A       B    C
0       t       8    10.96
1       w       2    98.63

Upvotes: 8

piroot
piroot

Reputation: 772

Since 0.17.0 version you can do .round(n)

df.round(2)
      0     1     2     3
0  0.06  0.67  0.77  0.71
1  0.80  0.56  0.97  0.15
2  0.03  0.59  0.11  0.95
3  0.33  0.19  0.46  0.92

df
          0         1         2         3
0  0.057116  0.669422  0.767117  0.708115
1  0.796867  0.557761  0.965837  0.147157
2  0.029647  0.593893  0.114066  0.950810
3  0.325707  0.193619  0.457812  0.920403

Upvotes: 52

user1839053
user1839053

Reputation:

that: data.apply(lambda x: np.round(x, decimals=2)) --- timeit.timer for 100x: 0.00356676544494

is same, but slower, as that: np.round(data,decimals=2) --- timeit.timer for 100x: 0.000921095

for example both gives:

                    x     y     z
Input Sequence                   
1                5.60  0.85 -6.50
2                5.17  0.72 -6.50
3                5.60  0.89 -6.28
4                5.17  0.76 -6.29

for data:

                      x       y       z
Input Sequence                         
1                5.6000  0.8519 -6.5000
2                5.1730  0.7151 -6.5000
3                5.6000  0.8919 -6.2794
4                5.1724  0.7551 -6.2888
5                5.6000  0.9316 -6.0587

Upvotes: 2

Tristan Forward
Tristan Forward

Reputation: 3524

import numpy as np
np.round(p_table, decimals=2)

Upvotes: 26

Related Questions