numpy max vs amax vs maximum
numpy has three different functions which seem like they can be used for the same things --- except that
numpy.maximum can only be used element-wise, while
numpy.amax can be used on particular axes, or all elements. Why is there more than just
numpy.max? Is there some subtlety to this in performance?
np.max is just an alias for
np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an
axis argument and will find the maximum value along an axis of the input array (returning a new array).
>>> a = np.array([[0, 1, 6], [2, 4, 1]]) >>> np.max(a) 6 >>> np.max(a, axis=0) # max of each column array([2, 4, 6])
The default behaviour of
np.maximum is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:
>>> b = np.array([3, 6, 1]) >>> c = np.array([4, 2, 9]) >>> np.maximum(b, c) array([4, 6, 9])
np.maximum is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):
>>> d = np.array([2, 0, 3, -4, -2, 7, 9]) >>> np.maximum.accumulate(d) array([2, 2, 3, 3, 3, 7, 9])
This is not possible with
You can make
np.max to a certain extent when using
>>> np.maximum.reduce(d) 9 >>> np.max(d) 9
Basic testing suggests the two approaches are comparable in performance.
★ Back to homepage or read more recommendations: