Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right way to round pandas.DataFrame?

I want round pandas.DataFrame.

Here is what i have tried so far:

import pandas as pd
data = pd.DataFrame([1.4,2.5,3.8,4.4,5.6],[6.2,7.6,8.8,9.1,0])
print(round(data))

But when i run this code, i get the following error:

Traceback (most recent call last):
  File "C:\Users\*****\Documents\*****\******\****.py", line 3, in <module>
    print(round(data))
TypeError: type DataFrame doesn't define __round__ method

What is the right way to round pandas.DataFrame ?

like image 465
Michael Avatar asked Dec 08 '13 15:12

Michael


People also ask

How do you round numbers in pandas series?

Pandas Series: round() functionThe round() function is used to round each value in a Series to the given number of decimals. Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.

What does round () do in pandas?

The round() method rounds the values in the DataFrame into numbers with the specified number of decimals, default 0 decimals.

How do you round to 2 decimal places in Python?

Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2.


1 Answers

first, you may want to change the definition of your data frame, something like:

data = pd.DataFrame([[1.4,2.5,3.8,4.4,5.6],[6.2,7.6,8.8,9.1,0]]).T

which results this:

     0    1
0  1.4  6.2
1  2.5  7.6
2  3.8  8.8
3  4.4  9.1
4  5.6  0.0

or:

data = pd.DataFrame({'A':[1.4,2.5,3.8,4.4,5.6],'B':[6.2,7.6,8.8,9.1,0]})

so that you get two columns, otherwise the other list is picked up as index; then:

data.apply(pd.Series.round)

or

import numpy as np
data.apply(np.round)
like image 174
behzad.nouri Avatar answered Oct 21 '22 12:10

behzad.nouri