[英]Identity value for numpy ufunc reducers
I have a numpy array which I want to find the maximum element of, so I call: 我有一个numpy数组,我想找到它的最大元素,所以我打电话给:
x = foo.max()
The problem is that foo
is sometimes an empty array, and the max
function (understandably) throws: 问题是
foo
有时是一个空数组,并且max
函数(可以理解)抛出:
ValueError: zero-size array to reduction operation maximum which has no identity
This leads to my question: 这引出了我的问题:
Is there a way to supply the identity value for the reduction operation? 有没有办法为还原操作提供标识值? (Ideally, one that will work for arbitrary numpy ufuncs with
reduce
methods.) Or am I stuck doing: (理想情况下,使用
reduce
方法可以使用任意numpy ufunc。)或者我坚持做:
if foo.size > 0:
x = foo.max()
else:
x = 0 # or whatever identity value I choose
Surely the "pythonic" way to go about this is: 当然,“pythonic”的方法是:
def safe_max(ar,default=np.nan):
try:
return np.max(ar)
except ValueError:
return default
x = safe_max(foo,0)
Considering that the maximum of an empty sequence is not defined, this would seem to also be the most logical approach. 考虑到未定义空序列的最大值,这似乎也是最合乎逻辑的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.