Thanks to visit codestin.com
Credit goes to github.com

Skip to content

np.random.choice unusable for array dimensions > 1 #10835

@pyformulas

Description

@pyformulas

NumPy version 1.14.2

It's not possible to grab a random row from a 2d array using np.random.choice. Consider this array:

points = np.random.random((10,2))

Trying to get a random row this way fails

np.random.choice(points)

ValueError: a must be 1-dimensional

which might be reasonable. (A more reasonable behavior is perhaps for np.random.choice to take an optional axis= argument so that it can return a random slice along the axis, defaulting to a random element in the entire array.)

However, there is no way to directly grab a random row:

np.random.choice(list(points))

ValueError: a must be 1-dimensional
np.random.choice(tuple(points))

ValueError: a must be 1-dimensional
np.random.choice([row for row in points])

ValueError: a must be 1-dimensional

Whereas this can be done with random.sample:

import random
random.sample(list(points), 1)

[array([0.77376144, 0.64678796])]

Metadata

Metadata

Assignees

No one assigned

    Labels

    57 - Close?Issues which may be closable unless discussion continued

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions