Issue
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].
Solution
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.])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.