Get random n rows from a 2D array in Python
In this tutorial, we are going to see how to get random n rows from a 2D array in Python. The 2D array is nothing but a matrix. This task can be done by using the Numpy library. We are going to see two methods for this.
First import the library
import numpy as np
Now define a 2D array using the
array() function from the Numpy library
arr = np.array([[0,1,2], [3,4,5], [6,7,8]])
shuffle( ) method to randomly get rows
shuffle() is a function from a random module. It is a module present in the Numpy library. It has a function shuffle which shuffles the given data randomly.
Now using this function shuffle the defined 2D array.
Now print the first two rows of the shuffled 2D array.
Note: You can print any n numbers of rows and columns from a 2D array using this method called slicing.
Here column numbers are not specified so it will return all the columns but 2 rows.
[[6 7 8] [0 1 2]]
randint( ) method: Get random n rows from a 2D array in Python
randint(start, stop, n) method is present in the random module. It is used to generate random integers between the start and stop.
The parameters of the function are:
1. start – Starting integer of range
2. stop – Ending integer of range
3. n – Number of random integers you want to generate between the range
Now, generate two random integers using this function. These two generated integers will be used as row numbers to select random rows from the 2D array.
n = np.random.randint(0,3,2) print(n)#n will be created as an array
In array indexing starts from 0 hence,
0 is the start point which is the minimum row index.
3 is the endpoint, the maximum number of rows present in an array.
2 is a number of random integers that should be generated.
Now print these rows from the 2D array
print(arr[n])#access 0th element of array n print(arr[n])
This will print the 1st and 0th row of the 2D array respectively.
[3 4 5] [0 1 2]
Also, refer to How to create a matrix of random numbers in Python