Heisenberg
Heisenberg

Reputation: 8806

Randomly sample rows (first dimension) of an array with unknown dimension

When the dimension is known, the task is trivial. Take a 2D array:

a = np.random.randint(10, a=(5,2))
a[np.random.choice(a.shape[0]), :]

However, in my function, the dimension of the array is arbitrary. How to handle this situation?

Upvotes: 1

Views: 208

Answers (1)

hpaulj
hpaulj

Reputation: 231385

use the size of the 1st dimension to determine the random range:

a[np.random.randint(0,a.shape[0],10)]

or if you prefer, include an Ellipsis

a[np.random.randint(0,a.shape[0],10),...]

1 indexing array selects from rows by default.

Upvotes: 2

Related Questions