我得到一个案例,当我尝试使用 np.max()
时在一个空的 numpy 数组中,它将报告此类错误消息。
# values is an empty numpy array here
max_val = np.max(values)
ValueError: zero-size array to reduction operation maximum which has no identity
所以我认为修复它的方法是在调用
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);
或者像这样使用 try catch 方式 link .
所以我想知道对于这种尴尬的情况是否有更好的解决方案。
提前致谢。
PS:
抱歉之前没有给出清晰的描述。
最佳答案
In [3]: np.max([])
---------------------------------------------------------------------------
...
ValueError: zero-size array to reduction operation maximum which has no identity
但是检查文档。在较新
numpy
ufunc
喜欢 max
拿个 initial
允许您使用空数组的参数:In [4]: np.max([],initial=10)
Out[4]: 10.0
关于python - 如何将 np.max 用于没有 ValueError : zero-size array to reduction operation maximum which has no identity 的空 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59801341/