【发布时间】:2019-12-06 08:22:09
【问题描述】:
我是 pandas python 的新手,我在尝试对列中的所有值进行四舍五入时遇到了困难。例如,
Example
88.9
88.1
90.2
45.1
我尝试在下面使用我当前的代码,但它给了我:
AttributeError: 'str' 对象没有属性 'rint'
df.Example = df.Example.round()
【问题讨论】:
我是 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
【讨论】:
.astype(int)。
我无权发表评论。我的不是一个新的答案。这是两个答案的比较。其中只有一个工作如下。
首先我尝试了这个https://datatofish.com/round-values-pandas-dataframe/
df['DataFrame column'].apply(np.ceil)
它对我不起作用。
然后我尝试了上面的答案
np.ceil(df.Example).astype(int)
成功了。
我希望这会对某人有所帮助。
【讨论】: