Bow*_*eng 7 python arrays numpy python-3.x
我得到一个案例,当我尝试np.max()在一个空的 numpy 数组中使用时,它会报告这样的错误消息。
# values is an empty numpy array here
max_val = np.max(values)
Run Code Online (Sandbox Code Playgroud)
ValueError:零大小数组到没有标识的缩减操作最大值
所以我认为修复它的方法是在调用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);
Run Code Online (Sandbox Code Playgroud)
或者使用像这个链接这样的 try catch 方式。
所以我想知道对于这种尴尬的情况是否有更好的解决方案。
提前致谢。
PS:抱歉之前没有给出清晰的描述。
hpa*_*ulj 13
In [3]: np.max([])
---------------------------------------------------------------------------
...
ValueError: zero-size array to reduction operation maximum which has no identity
Run Code Online (Sandbox Code Playgroud)
但是检查文档。在较新的numpy ufunclike 中max使用一个initial参数,让您可以使用空数组:
In [4]: np.max([],initial=10)
Out[4]: 10.0
Run Code Online (Sandbox Code Playgroud)