[Numpy-discussion] Broadcasting with np.logical_and.reduce

Antony Lee antony.lee at berkeley.edu
Fri Sep 12 12:44:25 EDT 2014


I see.  I went back to the documentation of ufunc.reduce and this is not
explicitly mentioned although a posteriori it makes sense; perhaps this can
be made clearer there?
Antony

2014-09-12 2:22 GMT-07:00 Robert Kern <robert.kern at gmail.com>:

> On Fri, Sep 12, 2014 at 10:04 AM, Antony Lee <antony.lee at berkeley.edu>
> wrote:
> > I am not using asarray here.  Sorry, but I don't see how this is
> relevant --
> > my comparison with np.add.reduce is simply that when a list of float
> arrays
> > is passed to np.add.reduce, broadcasting happens as usual, but not when a
> > list of bool arrays is passed to np.logical_and.reduce.
>
> But np.logical_and.reduce() *does* use asarray() when it is given a
> list object (all ufunc .reduce() methods do this). In both cases, you
> get a dtype=object array. This means that the ufunc will use the
> dtype=object inner loop, not the dtype=bool inner loop. For np.add,
> this isn't a problem. It just calls the __add__() method on the first
> object which, since it's an ndarray, calls np.add() again to do the
> actual work, this time using the appropriate dtype inner loop for the
> inner objects. But np.logical_and is different! For the dtype=object
> inner loop, it directly calls bool(x) on each item of the object
> array; it doesn't defer to any other method that might do the
> computation. bool(almost_any_ndarray) raises the ValueError that you
> saw. np.logical_and.reduce([x, y]) is not the same as
> np.logical_and(x, y). You can see how the dtype=object inner loop of
> np.logical_and() works by directly constructing dtype=object shape-()
> arrays:
>
> [~]
> |14> x
> array(None, dtype=object)
>
> [~]
> |15> x[()] = np.array([True, False])
>
> [~]
> |16> x
> array(array([ True, False], dtype=bool), dtype=object)
>
> [~]
> |17> y = np.array(None, dtype=object)
>
> [~]
> |18> y[()] = np.array([[True], [False]])
>
> [~]
> |19> y
> array(array([[ True],
>        [False]], dtype=bool), dtype=object)
>
> [~]
> |20> np.logical_and(x, y)
> ---------------------------------------------------------------------------
> ValueError                                Traceback (most recent call last)
> <ipython-input-20-17705aa17a6f> in <module>()
> ----> 1 np.logical_and(x, y)
>
> ValueError: The truth value of an array with more than one element is
> ambiguous. Use a.any() or a.all()
>
> --
> Robert Kern
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20140912/f4818b01/attachment.html>


More information about the NumPy-Discussion mailing list