1

I am using numpy.where, and I was wondering if there was a simply way to avoid calling the unused parameter. Example:

import numpy as np
z = np.array([-2, -1, 0, 1, -2])
np.where(z!=0, 1/z, 1)

returns:

array([-0.5, -1. ,  1. ,  1. , -0.5])

but I get a divide by zero warning because when z was 0, the code still evaluates 1/z even though it doesn't use it.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
Peter
  • 377
  • 1
  • 4
  • 15
  • why don't you use z = z[np.nonzero(z)] then divide by z, but that just returns 1 so I guess I am not sure why –  Jul 09 '16 at 00:20
  • `1/z` is executed by the interpreter as part of calling `where`. That's not under the control of `where`. But you can do `out[ind]=1/z[ind]` where `ind` is the mask of ok values. There are other ways of dealing divide by zero. – hpaulj Jul 09 '16 at 01:43
  • Search for the [numpy] and [divide-by-zero] tags – hpaulj Jul 09 '16 at 01:52

3 Answers3

2

You can also turn off the warning and turn it back on after you are done using the context manager errstate:

with np.errstate(divide='ignore'):
    np.where(z!=0, 1/z, 1)
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
1

You can apply a mask:

out = numpy.ones_like(z)
mask = z != 0
out[mask] = 1/z[mask]
Benjamin
  • 11,560
  • 13
  • 70
  • 119
0

scipy has a little utility just for this purpose: https://github.com/scipy/scipy/blob/master/scipy/_lib/_util.py#L26

It's basically a matter of allocating the output array and using np.place (or putmask) to fill exactly what you need.

ev-br
  • 24,968
  • 9
  • 65
  • 78