Home > front end >  Numpy random choice preserving original ordering
Numpy random choice preserving original ordering

Time:09-22

Let's say we have an array a = [5, 2, 3, 8, 4, 1, 9]

I want to choose a few elements (without replacement) so that the relative order of the chosen elements will be the same as in an input array. Using the random.choice with shuffle=False doesn't seem to do this.

a = [5, 2, 3, 8, 4, 1, 9]
rng = np.random.default_rng(42)
rng.choice(a, 4, replace=False, shuffle=False)

Output:

array([9, 5, 1, 8])

I want to see:

array([5, 8, 1, 9])

What's the simplest way to achieve this result?

CodePudding user response:

One method I can think of is to randomly choose indices first, and then filter the original list according to this set of indices:

import random

a = [5, 2, 3, 8, 4, 1, 9]

idx = set(random.sample(range(len(a)), k=4))
output = [x for i, x in enumerate(a) if i in idx]

print(output) # [5, 2, 3, 1]

Using numpy under the same idea,

import numpy as np
from numpy.random import default_rng

a = np.array([5, 2, 3, 8, 4, 1, 9])

output = a[sorted(default_rng().choice(range(len(a)), size=4, replace=False))]
print(output) # [5 3 4 9]

CodePudding user response:

Sample k random elements and sort the result according to the index in lst:

import random

def select_k_sorted(lst, k):
    return sorted(random.sample(lst, k), key=lst.index)
  • Related