我是pandas python的新手,我在尝试将列中所有的值四舍五入时遇到了困难。例如,
Example
88.9
88.1
90.2
45.1
我尝试使用下面的代码,但是它给我返回:
AttributeError: 'str'对象没有'rint'属性
df.Example = df.Example.round()
您可以使用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
我没有评论的权限。 我的不是新答案,而是两个答案的比较。 其中只有一个像下面这样工作。
首先,我尝试了这个 https://datatofish.com/round-values-pandas-dataframe/
df ['DataFrame column'] .apply(np.ceil)
对我不起作用。
然后我尝试了上面的答案
np.ceil(df.Example).astype(int)
它起作用了。
我希望这能帮到某人。
.astype(int)
。 - Ami Tavory