np.random.choice unusable for array dimensions > 1
See original GitHub issueNumPy 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])]
Issue Analytics
- State:
- Created 5 years ago
- Reactions:27
- Comments:9 (5 by maintainers)
Top Results From Across the Web
numpy.random.choice — NumPy v1.24 Manual
Generates a random sample from a given 1-D array ... If a is an int and less than zero, if a or p...
Read more >how to randomly sample in 2D matrix in numpy - Stack Overflow
Just use a random index (in your case 2 because you have 3 dimensions): import numpy as np Space_Position = np.array(Space_Position) ...
Read more >Numpy Random Seed, Explained - Sharp Sight
In this tutorial, I'll explain how to use the NumPy random seed function, which is also called np.random.seed or numpy.random.seed.
Read more >numpy.random.choice — NumPy v1.9 Manual
... size=None, replace=True, p=None)¶. Generates a random sample from a given 1-D array ... Generate a uniform random sample from np.arange(5) of size...
Read more >TFRecord and tf.train.Example | TensorFlow Core
Feature message type can accept one of the following three types (See the .proto file for ... feature0 = np.random.choice([False, True], n_observations)
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
You can sample a random set of row indices:
This also allows for sampling a random set of columns.
Those are from before adding
Generator.choice
, which solves the problem. We’d like to avoid changing the legacy functions at this point.That is a good point. I opened PR gh-16075 to do that.