将列向上取整

10

我是pandas python的新手,我在尝试将列中所有的值四舍五入时遇到了困难。例如,

Example
88.9
88.1
90.2
45.1

我尝试使用下面的代码,但是它给我返回:

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

 df.Example = df.Example.round()
2个回答

19

您可以使用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

根据你的喜好,你也可以更改类型:

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

编辑

您的错误信息表明,您只是想要进行四舍五入(不一定是向上取整),但是遇到了类型问题。您可以通过以下方式解决:

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

在这里,您也可以将其转换为整数类型:

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

嗨Ami,我尝试了df.Example.astype(float).round(),但它给了我.0小数点。有没有办法去掉小数点,只保留整数? - Jason Ching Yuk
@JasonChingYuk 正如我之前在答案中提到的,最后加上.astype(int) - Ami Tavory

0

我没有评论的权限。 我的不是新答案,而是两个答案的比较。 其中只有一个像下面这样工作。

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

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

对我不起作用。

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

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

它起作用了。

我希望这能帮到某人。


投票支持有效答案即可,无需评论,投票即表明它起作用了。 - Akber Iqbal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接