0
0
NumPydata~5 mins

Generating random samples in NumPy

Choose your learning style9 modes available
Introduction

We use random samples to create example data or simulate real-world situations where outcomes vary.

Testing a new data analysis method with fake data
Simulating dice rolls or coin flips in games
Creating random customer data for practice
Sampling a few items from a large dataset randomly
Syntax
NumPy
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.

Examples
Randomly picks 3 numbers from 0 to 4 (5 numbers total).
NumPy
import numpy as np
np.random.choice(5, size=3)
Randomly picks 2 different colors from the list without repeats.
NumPy
np.random.choice(['red', 'blue', 'green'], size=2, replace=False)
Randomly picks 4 numbers from the list with given probabilities.
NumPy
np.random.choice([10, 20, 30], size=4, replace=True, p=[0.1, 0.7, 0.2])
Sample Program

This program shows three ways to generate random samples using numpy:

  • Random numbers from 0 to 9
  • Unique fruits from a list
  • Numbers with specific chances
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)
OutputSuccess
Important Notes

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.

Summary

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.