[英]how to use np.max for empty numpy array without ValueError: zero-size array to reduction operation maximum which has no identity
I get a case that when I tried to use np.max()
in an empty numpy array it will report such error messages.我得到一个案例,当我尝试在一个空的 numpy 数组中使用np.max()
,它会报告这样的错误消息。
# values is an empty numpy array here
max_val = np.max(values)
ValueError: zero-size array to reduction operation maximum which has no identity ValueError:零大小数组到没有标识的缩减操作最大值
So the way I think to fix it is that I try to deal with the empty numpy array first before calling the np.max()
like follows:所以我认为修复它的方法是在调用np.max()
之前尝试先处理空的 numpy 数组,如下所示:
# add some values as missing values on purposes.
def deal_empty_np_array(a:np.array):
if a.size == 0:
a = np.append(a, [-999999, -999999])
return a
values = deal_empty_np_array(values)
max_val = np.max(values);
OR use the try catch way like this link .或者使用像这个链接这样的 try catch 方式。
So I am wondering if there is a better solution for this awkward case.所以我想知道对于这种尴尬的情况是否有更好的解决方案。
Thanks in advance.提前致谢。
PS: Sorry for not giving a clean description before. PS:抱歉之前没有给出清晰的描述。
In [3]: np.max([])
---------------------------------------------------------------------------
...
ValueError: zero-size array to reduction operation maximum which has no identity
But check the docs.但是检查文档。 In newer numpy
ufunc
like max
take an initial
parameter that lets you work with an empty array:在较新的numpy
ufunc
像max
接受一个initial
参数,让您可以使用空数组:
In [4]: np.max([],initial=10)
Out[4]: 10.0
I think you can simply check it, and eventually re-assign it, before calling np.max
:我认为您可以在调用np.max
之前简单地检查它,并最终重新分配它:
import numpy as np
values = -999 if values.size==0 else values
max_val = np.max(values)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.