w3resource

NumPy: Find the maximum and minimum value of a given flattened array


Write a Python program to find the maximum and minimum value of a given flattened array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a 2x2 array 'a' using arange and reshape
a = np.arange(4).reshape((2, 2))

# Displaying the original flattened array 'a'
print("Original flattened array:")
print(a)

# Finding and displaying the maximum value of the flattened array 'a' using np.amax()
print("Maximum value of the above flattened array:")
print(np.amax(a))

# Finding and displaying the minimum value of the flattened array 'a' using np.amin()
print("Minimum value of the above flattened array:")
print(np.amin(a)) 

Sample Output:

Original flattened array:
[[0 1]
 [2 3]]
Maximum value of the above flattened array:
3
Minimum value of the above flattened array:
0 

Explanation:

In the above exercise –

a = np.arange(4).reshape((2,2)): This line creates a 2D array of shape (2, 2) using the np.arange function and then reshape it to the desired shape using the reshape method.

np.amax(a): This code returns the maximum value of the entire array, which is 3.

np.amin(a): This code returns the minimum value of the entire array, which is 0.

Python-Numpy Code Editor: