【问题标题】:Rounding up a column四舍五入一列
【发布时间】: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()

【问题讨论】:

    标签: python pandas


    【解决方案1】:

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

    【讨论】:

    • 嘿,阿米,我试过 df.Example.astype(float).round() 但它给了我 0.0 小数点。有什么办法可以去掉小数点,只去掉整数?
    • @JasonChingYuk 正如我事先在答案中指出的那样,在末尾附加.astype(int)
    【解决方案2】:

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

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

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

    它对我不起作用。

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

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

    成功了。

    我希望这会对某人有所帮助。

    【讨论】:

    • 投票赞成有效的答案...无需评论,投票表明有效
    猜你喜欢
    • 2023-01-12
    • 2012-08-04
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2015-11-12
    • 1970-01-01
    相关资源
    最近更新 更多