Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the index of numpy.random.choice? - python

Tags:

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]).

like image 692
HappyPy Avatar asked Sep 13 '13 20:09

HappyPy


People also ask

How do I select a specific index in a NumPy array?

To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.

How do you select random elements from a NumPy array?

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)

Can you index a NumPy array?

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.


1 Answers

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 
like image 95
Óscar López Avatar answered Sep 18 '22 17:09

Óscar López