I'd like to sample from indices of a 2D Numpy array, considering that each index is weighted by the number inside of that array. The way I know it is with numpy.random.choice however that does not return the index but the number itself. Is there any efficient way of doing so?
Here is my code:
import numpy as np
A=np.arange(1,10).reshape(3,3)
A_flat=A.flatten()
d=np.random.choice(A_flat,size=10,p=A_flat/float(np.sum(A_flat)))
print d
np.indices(A), flatten the result(ing tuples) as well as your array of weights, use the linked method and your result is then given byflattened_indices_x[idx], flattened_indices[idx]. EDIT: Actually you can probably use docs.scipy.org/doc/numpy/reference/generated/… to avoid creating the index array and get the 2d index straight fromidxand your weights array shape.