Python 舍入 pandas.DataFrame 的正确方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20455163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:28:47  来源:igfitidea点击:

The right way to round pandas.DataFrame?

pythonpandasrounding

提问by Michael

I want round pandas.DataFrame.

我要圆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?

什么是圆的正确方法pandas.DataFrame

采纳答案by behzad.nouri

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)

回答by Vincent Claes

Since pandas 0.17.0 you can use

从熊猫 0.17.0 开始,您可以使用

DataFrame.round(decimals=0, *args, **kwargs)

If you want to round your data to 2 decimals do:

如果要将数据四舍五入为 2 位小数,请执行以下操作:

data.round(2)

more info here: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.round.html

更多信息:http: //pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.round.html