我有一个看起来像这样的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 :(得分:27)
您不能对作为对象的numpy数组进行舍入,只要您的数组可以安全地转换为浮点数,就可以使用astype
进行更改:
>>> 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])
您将收到与string,unicode,void和char类型数组类似的错误。
答案 1 :(得分:0)
你可以这样做:
numbers=[22.2,99.123,1213.1230]
newnumbers=[]
for n in numbers:
newnumbers.append(round(n))
#for comparison
print numbers
print newnumbers
答案 2 :(得分:0)
numpy.around
应该在列表列表中工作:
>>> import numpy as np
>>> arr = [[41.743617, -87.626839],
[41.936943, -87.669838],
[41.962665, -87.65571899999999]]
>>>
>>> np.around(arr, decimals=2)
array([[ 41.74, -87.63],
[ 41.94, -87.67],
[ 41.96, -87.66]])
>>> np.round(arr, decimals=2)
array([[ 41.74, -87.63],
[ 41.94, -87.67],
[ 41.96, -87.66]])
但请注意,它不适用于python longs。实际上它会报告您报告的相同错误:
>>> np.round(3892438942893489234899848939)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/csaftoiu/work/venv/lib/python2.7/site-packages/numpy/core/fromnumeric.py", line 2401, in round_
return _wrapit(a, 'round', decimals, out)
File "/Users/csaftoiu/work/venv/lib/python2.7/site-packages/numpy/core/fromnumeric.py", line 38, in _wrapit
result = getattr(asarray(obj),method)(*args, **kwds)
AttributeError: rint
似乎正在发生的是numpy无法将python列表中的某些数字转换为其中一种数据类型。如果它很长,那么它不是问题,因为它已经四舍五入,但你必须解决它。