How to Get Random Set of Rows from 2D NumPy Array?

In this tutorial, we will learn about the easiest way to get random set of rows from 2D NumPy array? By Pranit Sharma Last updated : May 28, 2023

Problem Statement

Suppose we are given a large two-dimensional array, and we need to find an easy way to get a new two-dimensional array that contains some random rows from the initial original array.

How to Get Random Set of Rows from 2D NumPy Array?

You can get a random set of rows from a 2D NumPy array using the numpy.random.randint() method within the array slicing by passing the maximum value that should be less than or equal to the total number of rows and size that can be considered as the number of rows to be extracted.

Explanation

Let suppose, you have a 2D NumPy array of 4 rows and you want to get 2 random rows from it. Consider the below-given statement:

numpy.random.randint(4, size=2)

This statement will return two random values between 0 to 4. Suppose the randomly generated values are 1 and 3. Thus, the returned value will be array(1, 3). Now, write the above statement within the array to extract these two rows.

arr[numpy.random.randint(4, size=2)]

This statement will return the rows 1 and 3.

Final Code Statements

You can use either of the code statements to get random values from a 2D NumPy array:

  • arr[numpy.random.randint(4, size=2)]
  • arr[numpy.random.randint(4, size=2), :]

Let us understand with the help of an example,

Python Program to Get Random Set of Rows from 2D NumPy Array

# Import numpy
import numpy as np

# Creating a numpy 2D array
arr = np.array([[1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16],
    [17, 18, 19, 20],
    [21, 22, 23, 24]])

# Printing original array
print("Original array:\n", arr, "\n")

# Get 2 random rows
res1 = arr[np.random.randint(6, size=2)]
# Get 3 random rows
res2 = arr[np.random.randint(6, size=3)]

# Printing specific columns
print("The 2 random rows (result 1):\n", res1)
print("The 3 random rows (result 2):\n", res2)

Output (Run 1)

Original array:
 [[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]
 [17 18 19 20]
 [21 22 23 24]] 

The 2 random rows (result 1):
 [[ 5  6  7  8]
 [13 14 15 16]]
The 3 random rows (result 2):
 [[17 18 19 20]
 [21 22 23 24]
 [21 22 23 24]]

Output (Run 2)

Original array:
 [[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]
 [17 18 19 20]
 [21 22 23 24]] 

The 2 random rows (result 1):
 [[ 5  6  7  8]
 [17 18 19 20]]
The 3 random rows (result 2):
 [[21 22 23 24]
 [ 5  6  7  8]
 [17 18 19 20]]

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.