To perform random sampling in Python, you can use the random module for lists and the sample method in pandas for DataFrames. Here are some common methods:
-
Sampling from a List:
- Use
random.sample for sampling without replacement.
- Use
random.choices for sampling with replacement.
-
Sampling from a Pandas DataFrame:
- Use the
sample method with the frac parameter to sample a fraction of the DataFrame.
- Use the
sample method with the n parameter to sample a specific number of rows.
- Set
replace=True to sample with replacement.
- Use
random_state to ensure reproducibility.
-
Stratified Sampling:
- Use the
groupby method to group the DataFrame by the stratum column.
- Apply the
sample method to each group.
-
Systematic Sampling:
- Use slicing with a step parameter to select every k-th row.
Here's an example code to illustrate these methods:
import random
import pandas as pd
# Example list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Sample 3 items without replacement
sampled_list = random.sample(my_list, 3)
print("Sample without replacement:", sampled_list)
# Sample 3 items with replacement
sampled_list_with_replacement = random.choices(my_list, k=3)
print("Sample with replacement:", sampled_list_with_replacement)
# Example DataFrame
data = {'A': range(1, 101), 'B': range(101, 201)}
df = pd.DataFrame(data)
# Sample 10% of the DataFrame without replacement
sampled_df = df.sample(frac=0.1, random_state=42)
print("\nSample 10% of DataFrame without replacement:")
print(sampled_df)
# Sample 10 rows with replacement
sampled_df_with_replacement = df.sample(n=10, replace=True, random_state=42)
print("\nSample 10 rows with replacement:")
print(sampled_df_with_replacement)
# Example DataFrame with a stratum column
data = {'A': range(1, 101), 'B': range(101, 201), 'Stratum': ['Group1']*50 + ['Group2']*50}
df = pd.DataFrame(data)
# Stratified sampling: sample 10% from each stratum
sampled_df_stratified = df.groupby('Stratum', group_keys=False).apply(lambda x: x.sample(frac=0.1, random_state=42))
print("\nStratified sampling (10% from each stratum):")
print(sampled_df_stratified)
# Systematic sampling: select every 10th row
sampled_df_systematic = df.iloc[::10]
print("\nSystematic sampling (every 10th row):")
print(sampled_df_systematic)
This code demonstrates how to perform various types of random sampling in Python, including sampling from lists, DataFrames, stratified sampling, and systematic sampling.