【发布时间】:2011-03-08 18:47:55
【问题描述】:
如果我有一个数组并且我想将值设置为“接近”某个值作为该值,那么最好的方法是什么?我想知道它们是否是一个 numpy 函数。如果没有 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]
【问题讨论】:
-
我认为这是“数据清理”的最佳方式。前段时间我问了一个关于数据清理的类似问题,你的方法是推荐的。 stackoverflow.com/questions/4339273/…