pandas 舍入一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38893170/
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-09-14 01:47:34  来源:igfitidea点击:

Rounding up a column

pythonpandas

提问by Jason Ching Yuk

I am new to pandas python and I am having difficulties trying to round up all the values in the column. For example,

我是 Pandas python 的新手,我在尝试收集列中的所有值时遇到了困难。例如,

Example
88.9
88.1
90.2
45.1

I tried using my current code below, but it gave me:

我尝试使用下面的当前代码,但它给了我:

AttributeError: 'str' object has no attribute 'rint'

AttributeError: 'str' 对象没有属性 'rint'

 df.Example = df.Example.round()

回答by Ami Tavory

You can use numpy.ceil:

您可以使用numpy.ceil

In [80]: import numpy as np

In [81]: np.ceil(df.Example)
Out[81]: 
0    89.0
1    89.0
2    91.0
3    46.0
Name: Example, dtype: float64

depending on what you like, you could also change the type:

根据您的喜好,您还可以更改类型:

In [82]: np.ceil(df.Example).astype(int)
Out[82]: 
0    89
1    89
2    91
3    46
Name: Example, dtype: int64


Edit

编辑

Your error message indicates you're trying just to round (not necessarily up), but are having a type problem. You can solve it like so:

您的错误消息表明您只是在尝试舍入(不一定是向上舍入),但遇到了类型问题。你可以这样解决:

In [84]: df.Example.astype(float).round()
Out[84]: 
0    89.0
1    88.0
2    90.0
3    45.0
Name: Example, dtype: float64

Here, too, you can cast at the end to an integer type:

在这里,您也可以在末尾强制转换为整数类型:

In [85]: df.Example.astype(float).round().astype(int)
Out[85]: 
0    89
1    88
2    90
3    45
Name: Example, dtype: int64

回答by Srikrishna Krishnarao Srinivas

I don't have privilege to comment. Mine is not a new answer. It is a compare of two answers. Only one of them worked as below.

我没有评论的权利。我的不是新答案。这是两个答案的比较。其中只有一个如下工作。

  1. First I tried this https://datatofish.com/round-values-pandas-dataframe/

    df['DataFrame column'].apply(np.ceil)

  1. 首先我尝试了这个https://datatofish.com/round-values-pandas-dataframe/

    df['DataFrame column'].apply(np.ceil)

It did not work for me.

它对我不起作用。

  1. Then I tried the above answer

    np.ceil(df.Example).astype(int)

  1. 然后我尝试了上面的答案

    np.ceil(df.Example).astype(int)

It worked.

有效。

I hope this will help someone.

我希望这会帮助某人。