# [Numpy-discussion] Re: selecting random array element

Robert Kern robert.kern at gmail.com
Mon Feb 20 15:47:01 CST 2006

```Chris Fonnesbeck wrote:
> What is the best way to select a random element from a numpy array? I
> know I could index by a random integer, but was wondering if there was
> a built-in method or function.

Generating a random index is what I do.

I think there's certainly room for a RandomState.choice() method. I think
something like this covers most of the use cases:

import numpy
from numpy import random
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 = numpy.asarray(x)
if axis is None:
length = numpy.multiply.reduce(x.shape)
n = random.randint(length)
return x.flat[n]
else:
n = random.randint(x.shape[axis])
# I'm sure there's a better way of doing this
idx = map(slice, x.shape)
idx[axis] = n
return x[tuple(idx)]

--
Robert Kern
robert.kern at gmail.com

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

```