[Numpy-discussion] Invalid value encoutered : how to, prevent numpy.where to do this?

Eric Emsellem eric.emsellem@eso....
Sat Jan 5 16:04:34 CST 2013


Thanks!

This makes sense of course. And yes the operation I am trying to do is 
rather complicated so I need to rely on a prior selection.

Now I would need to optimise this for large arrays and the code does go 
through these command line many many times.

When I have to operate on the two different parts of the array, I guess 
just using the following is the fastest way (as you indicated) :

result = np.empty_like(data)
mask = (data == 0)
result[mask] = 0.0
result[~mask] = 1.0/data[~mask]

But if I only need to do this on one side of the selection, I guess I 
would just do:

result = np.empty_like(data)
mask = (data != 0)
result[mask] += 1.0 / data[mask]

I have tried using three version of "mask = " with the rest of the code 
being the same:

1- mask = where(data != 0)
2- mask = np.where(data != 0)
3- mask = (data != 0)

and it looks like #3 is the fastest, then #2 (20% slower) then #1 (50% 
slower than #3).

I am not sure why, but Is that making sense? Or is there even a faster 
way (for large data arrays, and complicated operations)?

thanks

Eric
> If your operation doesn't factor like this though then you can always
> use something more cumbersome like
>    result = np.empty_like(data)
>    mask = (data == 0)
>    result[mask] = 0
>    result[~mask] = 1.0/data[~mask]
>
> Or in 1.7 this could be written
>    result = np.zeros_like(data)
>    np.divide(1.0, data, where=(data != 0), out=result)
>
> -n
>



More information about the NumPy-Discussion mailing list