w3resource

NumPy: Create a random 10x4 array and extract the first five rows of the array and store them into a variable


Write a NumPy program to create a random 10x4 array and extract the first five rows of the array and store them into a variable.

Sample Solution :

Python Code :

# Importing the NumPy library as np
import numpy as np

# Generating a 10x4 NumPy array 'x' filled with random floats between 0 and 1 using np.random.rand()
x = np.random.rand(10, 4)

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

# Selecting the first 5 rows of the array 'x' and storing it in variable 'y' using array slicing
y = x[:5, :]

# Printing the first 5 rows of the original array 'x' stored in 'y'
print("First 5 rows of the above array:")
print(y) 

Sample Output:

Original array:                                                        
[[ 0.38593391  0.52823544  0.8994567   0.22097238]                     
 [ 0.16639229  0.74964167  0.58102198  0.2811601 ]                     
 [ 0.56447627  0.42575759  0.71297527  0.91099347]                     
 [ 0.00261548  0.0064798   0.66096109  0.54514293]                     
 [ 0.7216008   0.95815426  0.53370551  0.28116107]                     
 [ 0.16252081  0.26191659  0.40883164  0.60653848]                     
 [ 0.55934457  0.37814126  0.63287808  0.01856616]                     
 [ 0.03788236  0.22705078  0.82024426  0.83019741]                     
 [ 0.31140166  0.43926341  0.38685152  0.92402934]                     
 [ 0.00581032  0.83925377  0.95246879  0.28570894]]                    
First 5 rows of the above array:                                       
[[ 0.38593391  0.52823544  0.8994567   0.22097238]                     
 [ 0.16639229  0.74964167  0.58102198  0.2811601 ]                     
 [ 0.56447627  0.42575759  0.71297527  0.91099347]                     
 [ 0.00261548  0.0064798   0.66096109  0.54514293]                     
 [ 0.7216008   0.95815426  0.53370551  0.28116107]]

Explanation:

In the above code –

x = np.random.rand(10, 4): This line generates a 2-dimensional array (10x4) of random floating-point numbers using the np.random.rand() function. The input arguments 10 and 4 specify the shape of the array, which has 10 rows and 4 columns.

y = x[:5, :]: This line uses slicing to extract the first 5 rows (rows 0 to 4) of the x array. The colon : before 5 in the row slicing [:5] denotes the start of the range, which is the first row (0). The colon in the column slicing [:, :] means that all columns will be included.

print(y): This line prints the new array y, which contains the first 5 rows of the original array x

Pictorial Presentation:

NumPy Random: Create a random 10x4 array and extract the first five rows of the array and store them into a variable.

Python-Numpy Code Editor: