Is it possible to modify the numpy.random.choice function in order to make it return the index of the chosen element? Basically, I want to create a list and select elements ran
Based on your comment:
The sample is already
a
. I want to work directly witha
so that I can control how many elements are still left and perform other operations witha
. – HappyPy
it sounds to me like you're interested in working with a
after n
randomly selected elements are removed. Instead, why not work with N = len(a) - n
randomly selected elements from a
? Since you want them to still be in the original order, you can select from indices like in @CTZhu's answer, but then sort them and grab from the original list:
import numpy as np
n = 3 #number to 'remove'
a = np.array([1,4,1,3,3,2,1,4])
i = np.random.choice(np.arange(a.size), a.size-n, replace=False)
i.sort()
a[i]
#array([1, 4, 1, 3, 1])
So now you can save that as a
again:
a = a[i]
and work with a
with n
elements removed.
Regarding your first question, you can work the other way around, randomly choose from the index of the array a
and then fetch the value.
>>> a = [1,4,1,3,3,2,1,4]
>>> a = np.array(a)
>>> random.choice(arange(a.size))
6
>>> a[6]
But if you just need random sample without replacement, replace=False
will do. Can't remember when it was firstly added to random.choice
, might be 1.7.0. So if you are running very old numpy
it may not work. Keep in mind the default is replace=True