The right way to round pandas.DataFrame?
Question:
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
?
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)
Since pandas 0.17.0 you can use
DataFrame.round(decimals=0, *args, **kwargs)
If you want to round your data to 2 decimals do:
data.round(2)
more info here:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.round.html
For those that come here but did not actually want to round the values, just when diplaying, use printoption as I explained in my other answer here
pd.set_option('precision', 3)
# or
from IPython.display import display
with pd.option_context('precision', 3):
display(pd.DataFrame(data={'x':[1,2,3],
'y':[4,5,6]}))
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
?
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)
Since pandas 0.17.0 you can use
DataFrame.round(decimals=0, *args, **kwargs)
If you want to round your data to 2 decimals do:
data.round(2)
more info here:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.round.html
For those that come here but did not actually want to round the values, just when diplaying, use printoption as I explained in my other answer here
pd.set_option('precision', 3)
# or
from IPython.display import display
with pd.option_context('precision', 3):
display(pd.DataFrame(data={'x':[1,2,3],
'y':[4,5,6]}))