Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

# values is an empty numpy array here
max_val = np.max(values)

ValueError: zero-size array to reduction operation maximum which has no identity

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:

# 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.

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.

like image 749
Bowen Peng Avatar asked Jan 18 '20 14:01

Bowen Peng


People also ask

Why does numpy empty have values?

NumPy empty produces arrays with arbitrary values empty function actually does fill the array with values. It's just that the values are completely arbitrary. The values are not quite “random” like the numbers you get from the np.

What is NP empty in numpy?

The numpy module of Python provides a function called numpy. empty(). This function is used to create an array without initializing the entries of given shape and type.

What does numpy Reduce do?

Reduces array 's dimension by one, by applying ufunc along one axis. For example, add. reduce() is equivalent to sum().


2 Answers

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:

In [4]: np.max([],initial=10)                                                                    
Out[4]: 10.0
like image 178
hpaulj Avatar answered Sep 17 '22 13:09

hpaulj


I think you can simply check it, and eventually re-assign it, before calling np.max:

import numpy as np

values = -999 if values.size==0 else values
max_val = np.max(values)
like image 32
FBruzzesi Avatar answered Sep 19 '22 13:09

FBruzzesi