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 randomly without replacement
import numpy as np >>> a = [1,4,1,3,3,2,1,4] >>> np.random.choice(a) >>> 4 >>> a >>> [1,4,1,3,3,2,1,4]
a.remove(np.random.choice(a))
will remove the first element of the list with that value it encounters (a[1]
in the example above), which may not be the chosen element (eg, a[7]
).
To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.
choice() function is used to get random elements from a NumPy array. It is a built-in function in the NumPy package of python. Parameters: a: a one-dimensional array/list (random sample will be generated from its elements) or an integer (random samples will be generated in the range of this integer)
ndarrays can be indexed using the standard Python x[obj] syntax, where x is the array and obj the selection. There are different kinds of indexing available depending on obj: basic indexing, advanced indexing and field access.
Here's one way to find out the index of a randomly selected element:
import random # plain random module, not numpy's random.choice(list(enumerate(a)))[0] => 4 # just an example, index is 4
Or you could retrieve the element and the index in a single step:
random.choice(list(enumerate(a))) => (1, 4) # just an example, index is 1 and element is 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With