Skip to content Skip to sidebar Skip to footer

From A 2d Array, Create Another 2d Array Composed Of Randomly Selected Values From Original Array (values Not Shared Among Rows) Without Using A Loop

To select random values from a 2d array, you can use this pool = np.random.randint(0, 30, size=[4,5]) seln = np.random.choice(pool.reshape(-1), 3, replace=False) print(pool) prin

Solution 1:

Here's a way avoiding for loops:

pool =  np.random.randint(0, 30, size=[4,5])
print(pool)
array([[ 4, 18,  0, 15,  9],
       [ 0,  9, 21, 26,  9],
       [16, 28, 11, 19, 24],
       [20,  6, 13,  2, 27]])

# New array shape
new_shape = (pool.shape[0],3)

# Indices where to randomly choose from
ix = np.random.choice(pool.shape[1], new_shape)
array([[0, 3, 3],
       [1, 1, 4],
       [2, 4, 4],
       [1, 2, 1]])

So ix's rows are each a set of random indices from which pool will be sampled. Now each row is scaled according to the shape of pool so that it can be sampled when flattened:

ixs = (ix.T + range(0,np.prod(pool.shape),pool.shape[1])).T
array([[ 0,  3,  3],
       [ 6,  6,  9],
       [12, 14, 14],
       [16, 17, 16]])

And ixs can be used to sample from pool with:

pool.flatten()[ixs].reshape(new_shape)
array([[ 4, 15, 15],
       [ 9,  9,  9],
       [11, 24, 24],
       [ 6, 13,  6]]) 

Post a Comment for "From A 2d Array, Create Another 2d Array Composed Of Randomly Selected Values From Original Array (values Not Shared Among Rows) Without Using A Loop"