NumPy: Create random set of rows from 2D array
NumPy: Array Object Exercise-114 with Solution
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:
Previous: Write a NumPy program to build an array of all combinations of three numpy arrays.
Next: Write a NumPy program to find indices of elements equal to zero in a numpy array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/python-numpy-exercise-114.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics