w3resource

NumPy: Create a 5x5 array with random values and find the minimum and maximum values


4. 5x5 Array Min/Max

Write a NumPy program to create a 5x5 array with random values and find the minimum and maximum values.

Sample Solution :

Python Code :

# Importing the NumPy library as np

import numpy as np

# Generating a 5x5 NumPy array 'x' filled with random floats between 0 and 1 using np.random.random()

x = np.random.random((5, 5))

# Printing the original array 'x'
print("Original Array:")
print(x)

# Calculating the minimum and maximum values in array 'x' using x.min() and x.max() functions
xmin, xmax = x.min(), x.max()

# Printing the minimum and maximum values of the array 'x'
print("Minimum and Maximum Values:")
print(xmin, xmax) 

Sample Output:

Original Array:                                                        
[[ 0.3839264   0.6527485   0.41092465  0.63987331  0.72739435]         
 [ 0.1711146   0.7542493   0.30799339  0.79689356  0.92014308]         
 [ 0.14420449  0.28689129  0.69339598  0.26608753  0.20895817]         
 [ 0.20215693  0.36993965  0.21283682  0.33183608  0.92672618]         
 [ 0.25734144  0.01083637  0.41502065  0.90604563  0.92236538]]        
Minimum and Maximum Values:                                            
0.0108363710034 0.926726177113

Explanation:

In the above exercise –

x = np.random.random((5,5)): This code generates a 2-dimensional array (5x5) of random floating-point numbers using the np.random.random() function. The input tuple (5,5) specifies the shape of the array, which has 5 rows and 5 columns.

xmin, xmax = x.min(), x.max(): This code calculates the minimum and maximum values present in the x array using the min() and max() methods, respectively. These values are then assigned to the variables xmin and xmax.

print(xmin, xmax): This line prints the minimum and maximum values (xmin and xmax) found in the x array.

Pictorial Presentation:

NumPy Random: Create a 5x5 array with random values and find the minimum and maximum values

For more Practice: Solve these Related Problems:

  • Create a 5x5 array of random numbers and compute both the overall minimum and maximum using vectorized operations.
  • Implement a function that returns the row-wise minimum and maximum values for a 5x5 array.
  • Replace the maximum value in each row of a 5x5 array with the corresponding row’s minimum value.
  • Find the indices of the minimum and maximum values in a 5x5 array and use them to swap these elements.

Go to:


PREV : 3x3x3 Random Array.
NEXT : Extract First 5 Rows of 10x4 Array.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.