Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

[EDIT] Figured it out.

import numpy as np np.round(p_table, decimals=2) 
like image 344
Tristan Forward Avatar asked Aug 12 '14 18:08

Tristan Forward


People also ask

How do you round a string to two decimal places in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

How do you round decimals in Python?

Round() Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.


2 Answers

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 
like image 147
piroot Avatar answered Sep 18 '22 02:09

piroot


import numpy as np np.round(p_table, decimals=2) 
like image 20
Tristan Forward Avatar answered Sep 21 '22 02:09

Tristan Forward