4

If I have an array and I want to set values 'close' to some value as that value, what is the best way to do this? I'm wondering if their is a numpy function for this. If there is no numpy function, then is the code below the "best" (i.e. quickest/most efficient) way to do this? It works for multi-dimensional arrays as well.

Code:

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]
1
  • I think that's the best way of 'data cleansing'. I asked a similar question on data cleansing a while ago, and your method is what was recommended. stackoverflow.com/questions/4339273/… Commented Mar 9, 2011 at 17:31

2 Answers 2

3

It's not so quite clear what you are trying to achieve, but my interpretation is that around is the solution for your case.

Sign up to request clarification or add additional context in comments.

2 Comments

This is probably the closest to what I want. However, it doesn't always do the exact same thing. For example, with my code above, I could set all values in an array within the range of [val-tol,val+tol] to some value, without changing (i.e. rounding) any other values in the array. Say I wanted to change all values in the interval [-3,3] to 0.0 without changing values outside the range of [-3,3], then around wouldn't work. With that said, it does work for just small tolerances and will work for my current purpose.
@Scott B: You may want to work only with those elements fulfilling some conditions. For example L= (-3< t)& (t< 3), t[L]= around(t[L], ...). Thanks
3

http://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html

1 Comment

But this wouldn't round a value of +1.0e-8 to 0.0. It would change a value of -1.0e-8 to 0.0 though (both of these using a clip of something similar to [0,1]). However, I'm glad you pointed out this function as it will be useful for my task as well...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.