Why does numpy.random.choice not work the same as random.choice? When I do this :
>>> random.choice([(1,2),(4,3)])
(1, 2)
It works.
But when I do this:
>>> np.random.choice([(1,2), (3,4)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mtrand.pyx", line 1393, in mtrand.RandomState.choice
(numpy/random/mtrand/mtrand.c:15450)
ValueError: a must be 1-dimensional
How do I achieve the same behavior as random.choice() in numpy.random.choice()?
Well
np.random.choice
as noted in the docs, expects a 1D array and your input when expressed as an array would be2D
. So, it won't work simply like that.To make it work, we can feed in the length of the input and let it select one index, which when indexed into the input would be the equivalent one from
random.choice
, as shown below -Sample run -
Alternatively, we can convert the input to a 1D array of object dtype and that would allow us to directly use
np.random.choice
, as shown below -Relatedly, if you want to randomly sample rows of a 2D matrix like this
then you can do something like this:
Should work for a 2D matrix with any number of columns, and you can of course sample however many times you want with the
size
kwarg, etc.