Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Lowest Elementwise Values from Multiple Numpy Arrays Which May be Different Lengths

Tags:

python

numpy

I can get the lowest values from multiple arrays by using the following:

first_arr = np.array([0,1,2])
second_arr = np.array([1,0,3])
third_arr = np.array([3,0,4])
fourth_arr = np.array([1,1,9])

print(np.minimum.reduce([first_arr, second_arr, third_arr, fourth_arr]))

Result = [0 0 2]

However if the arrays are different lengths or empty I get an error:

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (4,) + inhomogeneous part.

The arrays will often be different lengths or empty. How can I handle this? I want to compare all elements that exist.

So, changing the above example:

first_arr = np.array([0,1])
second_arr = np.array([1,0,3])
third_arr = np.array([3,0,4])
fourth_arr = np.array([1,1,9])

print(np.minimum.reduce([first_arr, second_arr, third_arr, fourth_arr]))

The result should be [0 0 3].

like image 596
James Avatar asked Dec 28 '25 06:12

James


2 Answers

If you don't mind the overhead, use pandas's DataFrame.min:

l = [first_arr, second_arr, third_arr, fourth_arr]

out = pd.DataFrame(l).min().to_numpy()

Or with itertools.zip_longest and numpy.nanmin:

from itertools import zip_longest

l = [first_arr, second_arr, third_arr, fourth_arr]

out = np.nanmin(np.c_[list(zip_longest(*l, fillvalue=np.nan))], axis=1)

Output: array([0., 0., 3.])

like image 129
mozway Avatar answered Dec 30 '25 22:12

mozway


Another solution, use itertools.zip_longest:

from itertools import zip_longest

lst = [first_arr, second_arr, third_arr, fourth_arr]
out = [min(arr) for arr in zip_longest(*lst, fillvalue=float("inf"))]
print(out)  # or print(np.array(out)) to have output as np.array

Prints:

[0, 0, 3]
like image 36
Andrej Kesely Avatar answered Dec 30 '25 22:12

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!