Random Sampling with .choice
- 01:32
How to use the random choice function from Python's random module to sample elements from an array.
Downloads
No associated resources to download.
Glossary
Choice Function NumPy Numpy arrays Python Random ChoiceTranscript
Another useful function in the random module is random choice. Now here I've created a new array called ordered array, and to do that I've used the range function, which is an easy way to create integers in sequence. So I've created an array with the numbers 1 through 10.
Now down here I've set the random seed to 10 so that you can reproduce my results if you want to. Then I'm calling the choice function inside the random module, and the choice function takes two arguments. The first is the array that you want to sample from. So here I'm taking a sample from ordered array, and the second argument is simply the number of objects that you want to take in that sample.
When I execute the cell, I'll get 10, 5, 1, 2, and 10, and this is a good example because we're getting 10 twice, which tells you that choice is sampling. With replacement, it'll take 10 as the first object, and then it puts it back into ordered array, and then it makes its next random choice, which is five, which is unique, one is unique, two is unique, and then it grabs 10 again just by chance. If you want all of the samples in choice to be unique, then just past the argument, replace equals false, and that means that choice will not sample with replacement. When I execute that code cell, you'll see that all of the objects that I sample now are unique.