[SciPy-User] Populate an array with integers (randomly, weighted)

Alan G Isaac alan.isaac at gmail.com
Tue Aug 27 13:50:59 EDT 2013


On 8/27/2013 3:54 AM, Johannes Radinger wrote:
> I'd like to randomly populate a numpy array (100,100) so that the numpy.sum() of the array equals exactly 300
> (e.g. distribute 300 rice grains on a chess board).

One possibility below.
Alan Isaac

 >>> wts = np.array([[3,2,0],[1,0,2]])
 >>> a = np.zeros(wts.shape)
 >>> accwts = np.cumsum(wts.flat)
 >>> draws = np.random.random((300)) * accwts[-1]
 >>> cts = np.bincount(np.digitize(draws,accwts),minlength=wts.size)
 >>> a.flat += cts
 >>> a
array([[ 107.,   83.,    0.],
        [  36.,    0.,   74.]])




More information about the SciPy-User mailing list