Introduction
We use random samples to create example data or simulate real-world situations where outcomes vary.
Jump into concepts and practice - no test required
We use random samples to create example data or simulate real-world situations where outcomes vary.
numpy.random.choice(a, size=None, replace=True, p=None)
a is the array or number of items to choose from.
size is how many samples you want.
import numpy as np np.random.choice(5, size=3)
np.random.choice(['red', 'blue', 'green'], size=2, replace=False)
np.random.choice([10, 20, 30], size=4, replace=True, p=[0.1, 0.7, 0.2])
This program shows three ways to generate random samples using numpy:
import numpy as np # Pick 5 random numbers from 0 to 9 samples = np.random.choice(10, size=5) print('Random samples:', samples) # Pick 3 unique fruits fruits = ['apple', 'banana', 'cherry', 'date'] unique_fruits = np.random.choice(fruits, size=3, replace=False) print('Unique fruits:', unique_fruits) # Pick 6 numbers with custom probabilities numbers = [1, 2, 3] probabilities = [0.5, 0.3, 0.2] samples_prob = np.random.choice(numbers, size=6, p=probabilities) print('Samples with probabilities:', samples_prob)
Setting replace=False means no repeats in samples.
Probabilities p must add up to 1.
Random results change each time unless you set a random seed.
Use numpy.random.choice to pick random samples from data.
You can control sample size, repetition, and probabilities.
Random sampling helps simulate and test data scenarios easily.
numpy.random.choice function do?numpy.random.choice is designed to pick random elements from a given array or list.arr without replacement using numpy?numpy.random.choice. To select 3 elements without replacement, use size=3 and replace=False.import numpy as np np.random.seed(0) arr = np.array([10, 20, 30, 40]) sample = np.random.choice(arr, size=2, replace=False) sample_sorted = np.sort(sample) sample_sorted.tolist()
import numpy as np arr = np.array([1, 2, 3]) sample = np.random.choice(arr, size=5, replace=False)
replace=False, p=[1/6]*6 incorrectly prevents repeats needed for multiple rolls. The codes with uniform probabilities (explicit [1/6,1/6,1/6,1/6,1/6,1/6] or none specified) do not weight side 6 twice as likely.