The right way to round pandas.DataFrame?

我是研究僧i 提交于 2019-12-22 03:37:08

问题


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 ?


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/20455163/the-right-way-to-round-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!