# [Numpy-discussion] Use-case for np.choose

Anne Archibald peridot.faceted@gmail....
Sat Nov 7 15:32:20 CST 2009

```2009/11/7 David Goldsmith <d.l.goldsmith@gmail.com>:
> Hi, all!  I'm working to clarify the docstring for np.choose (Stefan pointed
> out to me that it is pretty unclear, and I agreed), and, now that (I'm
> pretty sure that) I've figured out what it does in its full generality
> (e.g., when the 'choices' array is greater than 2-D), I'm curious as to
> use-cases.  (Not that I'm suggesting that we deprecate it, but I am curious
> as to whether or not anyone is presently using it and if so, how they're
> using it, esp. if anyone *is* using it with 'choices' arrays 3-D or
> greater.)

It's a generalized np.where(), allowing more than two options:

In [10]: a = np.arange(2*3*5).reshape(2,3,5) % 3

In [11]: o = np.ones((2,3,5))

In [12]: np.choose(a,(o,0.5*o,0.1*o))
Out[12]:
array([[[ 1. ,  0.5,  0.1,  1. ,  0.5],
[ 0.1,  1. ,  0.5,  0.1,  1. ],
[ 0.5,  0.1,  1. ,  0.5,  0.1]],

[[ 1. ,  0.5,  0.1,  1. ,  0.5],
[ 0.1,  1. ,  0.5,  0.1,  1. ],
[ 0.5,  0.1,  1. ,  0.5,  0.1]]])

> Also, my experimenting suggests that the index array ('a', the first
> argument in the func. sig.) *must* have shape (choices.shape[-1],) - someone
> please let me know ASAP if this is not the case, and please furnish me w/ a
> counterexample because I was unable to generate one myself.

It seems like a and each of the choices must have the same shape (with
the exception that choices acn be scalars), but I would consider this
a bug. Really, a and all the choices should be broadcast to the same
shape. Or maybe it doesn't make sense to broadcast a - it could be
valuable to know that the result is always exactly the same shape as a
- but broadcasting all the choice arrays presents an important
improvement of choose over fancy indexing. There's a reason choose
accepts a sequence of arrays as its second argument, rather than a
higher-dimensional array.

Anne

> Thanks,
>
> DG
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
```