使用numpy.round时出现“ AttributeError:rint”

发布于 2021-01-29 18:01:05

我有一个像这样的numpy数组:

[[41.743617 -87.626839]
 [41.936943 -87.669838]
 [41.962665 -87.65571899999999]]

我想将数组中的数字四舍五入到小数点后两位或三位。我尝试使用numpy.around和numpy.round,但是它们都给我以下错误:

  File "/Library/Python/2.7/site-packages/numpy-1.8.0.dev_3084618_20130514-py2.7-macosx-10.8-intel.egg/numpy/core/fromnumeric.py", line 2452, in round_
    return round(decimals, out)
AttributeError: rint

我曾经numpy.around(x, decimals = 2)numpy.round(x,decimals=2)

难道我做错了什么?还有其他方法可以有效地对大型阵列执行此操作吗?

关注者
0
被浏览
51
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您不能对作为对象的numpy数组进行四舍五入astype,只要可以将数组安全地转换为float即可更改此值:

    >>> a = np.random.rand(5).astype(np.object)
    >>> a
    array([0.5137250555772075, 0.4279757819721647, 0.4177118178603122,
           0.6270676923544128, 0.43733218329094947], dtype=object)
    
    >>> np.around(a,3)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/fromnumeric.py", line 2384, in around
        return round(decimals, out)
    AttributeError: rint
    
    >>> np.around(a.astype(np.double),3)
    array([ 0.514,  0.428,  0.418,  0.627,  0.437])
    

    对于字符串,unicode,void和char类型的数组,您将收到类似的错误。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看