[Numpy-discussion] random.choice

Alan G Isaac alan.isaac at gmail.com
Fri Nov 9 09:17:46 EST 2012

I just noticed that 1.7 is scheduled to add a random.choice function.
I wonder if the best structure has been chosen.  Specifically, it does
not provide for array flattening, and it does not provide for subarray

Back in 2006 (?) Robert Kern suggested something like the below
(forgive any mistranslation).  I think the included functionality
does belong in a choice function.  I do like the provision for
repeated sampling in the current proposal, however.

Alan Isaac

def choice(x, axis=None):
	"""Select an element or subarray uniformly randomly.
	If axis is None, then a single element is chosen from the entire array.
	Otherwise, a subarray is chosen from the given axis.
	x = np.asarray(x)
	if axis is None:
		length = np.multiply.reduce(x.shape)
		n = random.randint(length)
		return x.flat[n]
		n = random.randint(x.shape[axis])
		idx = map(slice, x.shape)
		idx[axis] = n
		return x[tuple(idx)]

More information about the NumPy-Discussion mailing list