Find the maximum and minimum element in a NumPy array
An array can be considered as a container with the same types of elements. Python has its array module named array. We can simply import the module and create our array. But this module has some of its drawbacks. The main disadvantage is we can’t create a multidimensional array. And the data type must be the same.
To overcome these problems we use a third-party module called NumPy. Using NumPy we can create multidimensional arrays, and we also can use different data types.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Note: NumPy doesn’t come with python by default. So, we have to install it using pip. To install the module run the given command in the terminal.
pip install numpy
Now let’s create an array using NumPy. For doing this we need to import the module. Here we’re importing the module.
Using the above command you can import the module.
Example 1: Now try to create a single-dimensional array.
arr = numpy.array([1, 2, 3, 4, 5])
Here, we create a single-dimensional NumPy array of integers. Now try to find the maximum element. To do this we have to use numpy.max(“array name”) function.
For finding the minimum element use numpy.min(“array name”) function.
maximum element in the array is: 8 minimum element in the array is: 1
Note: You must use numeric numbers(int or float), you can’t use string.
Example 2: Now, let’s create a two-dimensional NumPy array.
arr = numpy.array([11, 5, 7], [4, 5, 16], [7, 81, 16]]
Now using the numpy.max() and numpy.min() functions we can find the maximum and minimum element.
Here, we get the maximum and minimum value from the whole array.
maximum element in the array is: 81 minimum element in the array is: 2
Example 3: Now, if we want to find the maximum or minimum from the rows or the columns then we have to add 0 or 1. See how it works:
maximum_element = numpy.max(arr, 0) maximum_element = numpy.max(arr, 1)
If we use 0 it will give us a list containing the maximum or minimum values from each column. Here we will get a list like [11 81 22] which have all the maximum numbers each column.
If we use 1 instead of 0, will get a list like [11 16 81], which contain the maximum number from each row.
maximum elements in the columns of the array is: [11 81 22] maximum elements in the rows of the array is: [11 16 81] minimum elements in the columns of the array is: [4 2 3] minimum elements in the rows of the array is: [2 4 7]
Example 4: If we have two same shaped NumPy arrays, we can find the maximum or minimum elements. For this step, we have to numpy.maximum(array1, array2) function. It will return a list containing maximum values from each column.
[ 5 7 6 9 22]