如果我有一个数组,并且我想将值设置为“close”作为该值的某个值,那么执行此操作的最佳方法是什么?我想知道他们是否是一个numpy功能。如果没有numpy功能,那么代码是否低于“最佳”(即最快/最有效)的方式来做到这一点?它也适用于多维数组。Python/Numpy - 在值的某些公差范围内设置值
代码:
from numpy import array
tol = 1e-5
# Some array with values close to 0 and 1
t = array([1.0e-10, -1.0e-10, 1.0+1.0e-10, 1.0-1.0e-10, 5.0])
print t[0], t[1], t[2], t[3], t[4]
# Set values within 'tol' of zero to zero
t[abs(t) < tol] = 0.
print t[0], t[1], t[2], t[3], t[4]
# Set values within 'tol' of some value to that value
val = 1.
t[abs(t-val) < tol] = val
print t[0], t[1], t[2], t[3], t[4]
我认为这是'数据清理'的最佳方式。我刚才问了一个关于数据清理的类似问题,你的方法就是建议的。 http://stackoverflow.com/questions/4339273/can-i-cleanse-a-numpy-array-without-a-loop – Pete 2011-03-09 17:31:11