Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select two random rows from numpy array

I have a numpy array as

[[  5.80084178e-05   1.20779787e-02  -2.65970238e-02]
 [ -1.36810406e-02   6.85722519e-02  -2.60280724e-01]
 [  4.21996519e-01  -1.43644036e-01   2.12904690e-01]
 [  3.03098198e-02   1.50170659e-02  -1.09683402e-01]
 [ -1.50776089e-03   7.22369575e-03  -3.71181228e-02]
 [ -3.04448275e-01  -3.66987035e-01   1.44618682e-01]
 [ -1.46744916e-01   3.47112167e-01   3.09550267e-01]
 [  1.16567762e-03   1.72858807e-02  -9.39297514e-02]
 [  1.25896836e-04   1.61310167e-02  -6.00253128e-02]
 [  1.65062798e-02   1.96933143e-02  -4.26540031e-02]
 [ -3.78020965e-03   7.51770012e-03  -3.67852984e-02]]

And I want to select any two random rows from these so the output will be-

[[ -1.36810406e-02   6.85722519e-02  -2.60280724e-01]
[  1.16567762e-03   1.72858807e-02  -9.39297514e-02]]
like image 280
DummyGuy Avatar asked Apr 03 '14 11:04

DummyGuy


People also ask

How do I randomly select rows from NumPy array?

The shuffle() function shuffles the rows of an array randomly and then we will display a random row of the 2D array.

How do you take a random sample from an array in Python?

Use the numpy. random. choice() function to pick multiple random rows from the multidimensional array.

How do I select a row in NumPy?

We can use [][] operator to select an element from Numpy Array i.e. Example 1: Select the element at row index 1 and column index 2. Or we can pass the comma separated list of indices representing row index & column index too i.e.

How do I select a random number in NumPy?

The choice() method allows you to generate a random value based on an array of values. The choice() method takes an array as a parameter and randomly returns one of the values.


1 Answers

I believe you are simply looking for:

#Create a random array
>>> a = np.random.random((5,3))
>>> a
array([[ 0.26070423,  0.85704248,  0.82956827],
       [ 0.26840489,  0.75970263,  0.88660498],
       [ 0.5572771 ,  0.29934986,  0.04507683],
       [ 0.78377012,  0.66445244,  0.08831775],
       [ 0.75533819,  0.05128844,  0.49477196]])

#Select random rows based on the rows in your array
#The 2 value can be changed to select any number of rows
>>> b = np.random.randint(0,a.shape[0],2)
>>> b
array([1, 2])

#Slice array a
>>> a[b]
array([[ 0.26840489,  0.75970263,  0.88660498],
       [ 0.5572771 ,  0.29934986,  0.04507683]])

Or simply:

a[np.random.randint(0,a.shape[0],2)]
like image 77
Daniel Avatar answered Oct 07 '22 01:10

Daniel