What does the numpy.max function do?
I went for a piece of code that looks like this:
while numpy.max(abs(A - B)) > 0.01:
I'm trying to replace numpy.max
with some regular Python function (math?) But I can't seem to find what exactly does numpy.max
.
I tried googling but I only found:
numpy.maximum
which is not the same as numpy.max
I suppose.
A:
numpy.amax
that again is not what I need.
Does anyone know how I can replicate this numpy.max function to some standard python?
EDIT: I am using Python 2.7
source to share
You cannot replicate behavior very easily np.max
in pure Python, simply because multidimensional arrays are not standard in Python. If A
and B
in your code are such arrays, it would be better to keep the NumPy function.
For flat (one-dimensional) arrays, Python max
and np.max
do the same and can be swapped:
>>> a = np.arange(27)
>>> max(a)
26
>>> np.max(a)
26
For arrays with more than one dimension max
will not work:
>>> a = a.reshape(3, 3, 3)
>>> max(a)
ValueError: The truth value of an array with more than one element is ambiguous [...]
>>> np.max(a)
26
By default np.max
flattens the 3D array and returns the maximum. (You can also find the maximum along individual axes, etc.) Python max
cannot do this.
To replace np.max
, you need to write nested loops over the axes of the array; effectively trying to find the maximum in a list of nested lists. This is certainly possible, but it will probably be very slow:
>>> max([max(y) for y in x for x in a])
26
source to share
numpy.max
is the same as numpy.amax
:
>>> import numpy
>>> numpy.max # Notice it says 'amax' in the output
<function amax at 0x0228B5D0>
>>> numpy.max is numpy.amax
True
>>>
Or, more specifically, it max
is an alias for a function amax
.
The purpose of this function is listed in the docs link you gave, but it looks like it is mainly used to determine the maximum value inside a numpy.array
regardless of the number of nested levels. You can simulate this behavior with a simple function to flatten the list:
def flatten(lst):
for item in lst:
if isinstance(item, list):
# Use 'yield from flatten(item)' in Python 3.3 or greater
for sub_item in flatten(item):
yield sub_item
else:
yield item
and the built-in functionmax
:
max(flatten(my_list))
See demo below:
>>> def flatten(lst):
... for item in lst:
... if isinstance(item, list):
... for sub_item in flatten(item):
... yield sub_item
... else:
... yield item
...
>>> array = [[1, 2, 3], [4, 5, 6]]
>>> max(flatten(array))
6
>>>
source to share