Identifier value for numpy ufunc reducers

I have a numpy array that I want to find the maximum element, so I call:

x = foo.max()

The problem is that foosometimes it is an empty array, and the function max(understandably) throws:

ValueError: zero-size array to reduction operation maximum which has no identity

This leads to my question:

Is there a way to specify an identifier value for a shrink operation? (Ideally, one that will work for arbitrary numpy ufuncs with methods reduce.) Or I'm stuck:

if foo.size > 0:
  x = foo.max()
else:
  x = 0  # or whatever identity value I choose
+4
source share
1 answer

Of course, the "pythonic" way to do this is:

def safe_max(ar,default=np.nan):
    try:
        return np.max(ar)
    except ValueError:
        return default

x = safe_max(foo,0)

Given that the maximum of the empty sequence has not been determined, this, apparently, is also the most logical approach.

0

All Articles