NumPy: Create random set of rows from 2D array
Generate Random Rows from 2D Array
Write a NumPy program to create a random set of rows from a 2D array.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Creating a new 2D NumPy array 'new_array' with random integers between 0 and 4 inclusive
new_array = np.random.randint(5, size=(5, 3))
# Printing a message indicating a random set of rows from the 2D array will be displayed
print("Random set of rows from 2D array array:")
# Printing the generated 2D NumPy array 'new_array'
print(new_array)
Sample Output:
Random set of rows from 2D array array: [[4 0 2] [4 2 4] [1 0 4] [4 4 3] [3 4 3]]
Explanation:
In the above code –
np.random.randint(5, size=(5, 3)): Generate an array of random integers between 0 (inclusive) and 5 (exclusive). The size parameter is set to (5, 3), which specifies the shape of the resulting array, i.e., 5 rows and 3 columns. Store the generated array to the variable 'new_array'.
print(new_array): Print the resulting 'new_array'.
Pictorial Presentation:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics