w3resource

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: Create random set of rows from 2D array

For more Practice: Solve these Related Problems:

  • Write a NumPy program to randomly select a specified number of rows from a 2D array using np.random.choice.
  • Create a function that shuffles the rows of a matrix and returns a random subset of rows.
  • Test the random row selection on a large array to ensure no row is repeated unless intended.
  • Implement a solution that allows specifying a seed for reproducible random row generation.

Go to:


PREV : Build Array of All Combinations of Three Arrays
NEXT : Find Indices of Elements Equal to Zero


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.