Home > OS >  Maximum and Minimum values from multiple arrays in Python
Maximum and Minimum values from multiple arrays in Python

Time:07-16

I have two arrays X1 and X2. I want to find maximum and minimum values from these two arrays in one step. But it runs into an error. I present the expected output.

import numpy as np

X1 = np.array([[ 527.25      ],
       [2604.89634575],
       [ 946.77085166],
       [ 816.79051828],
       [1388.77873104],
       [4633.70349825],
       [1125.9493112 ],
       [1811.67700025],
       [ 718.19141262],
       [ 640.83306256],
       [ 578.51918766],
       [ 522.02970297]])   

X2 = np.array([[ 527.25      ],
       [2604.89634575],
       [ 941.87856824],
       [ 781.29465624],
       [1388.77873104],
       [4633.70349825],
       [1125.9493112 ],
       [1811.67700025],
       [ 319.09009796],
       [ 558.12142224],
       [ 484.73489944],
       [ 473.62756082]])  

Max=max(X1,X2)
Min=min(X1,X2)

The error is

in <module>
    Max=max(X1,X2)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The expected output is

array([4633.70349825])
array([319.09009796])

CodePudding user response:

You can use np.ufunc.reduce with multiple axis

(first find max on axis=1 from X1 , X2 then find max on axis=0 from result.)

np.maximum.reduce([X1, X2], axis=(1,0))
# array([4633.70349825])

np.minimum.reduce([X1, X2], axis=(1,0))
# array([319.09009796])

Or try this:

>>> max(max(X1), max(X2))
array([4633.70349825])

>>> min(min(X1), min(X2))
array([319.09009796])

CodePudding user response:

You need to wrap the arrays in a array-like object (list, tuple). See below:

ma = np.max([X1, X2])
mi = np.min([X1, X2])
print(ma)
print(mi)

Output

4633.70349825
319.09009796

By default both max and min will flatten the input, from the documentation:

axis None or int or tuple of ints, optional Axis or axes along which to operate. By default, flattened input is used.

  • Related