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.
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.
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.
Reduces array 's dimension by one, by applying ufunc along one axis. For example, add. reduce() is equivalent to sum().
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With