python - 如何将 np.max 用于没有 ValueError : zero-size array to reduction operation maximum which has no identity 的空 numpy 数组

标签 python arrays python-3.x numpy

我得到一个案例,当我尝试使用 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/

相关文章:

python - 如何用最少的代码在 Python 中绘制不同类型的混淆矩阵?

python - 无法使用绝对路径导入

python - Pandas 从数据帧中删除镜像对

c - 如何将字符串转换为二维数组

java - 排序列表的二维数组线性搜索

python - Maya 变换节点未出现在列表中

c++ - 字符串数组长度 C++ 问题?

python-3.x - 文本文件读写,ValueError : need more than 1 value to unpack

python - 使用 selenium 和 beautifulsoup 的慢代码

python-3.x - 如何修复 Colaboratory 中的 zipfile 读取错误?