This is my best solution so far. It is important to bin continuous variables before and to have a minimum of observations for each stratum.
In this example, I am :
- Generating a population
- Sampling in a pure random way
- Sampling in a random stratified way
When comparing both samples, the stratified one is much more representative of the overall population.
If anyone has an idea of a more optimal way to do it, please feel free to share.
import pandas as pd
import numpy as np
# Generate random population (100K)
population = pd.DataFrame(index=range(0,100000))
population['income'] = 0
population['income'].iloc[39000:80000] = 1
population['income'].iloc[80000:] = 2
population['sex'] = np.random.randint(0,2,100000)
population['age'] = np.random.randint(0,4,100000)
pop_count = population.groupby(['income', 'sex', 'age'])['income'].count()
# Random sampling (100 observations out of 100k)
random_sample = population.iloc[
np.random.randint(
0,
len(population),
int(len(population) / 1000)
)
]
# Random Stratified Sampling (100 observations out of 100k)
stratified_sample = list(map(lambda x : population[
(
population['income'] == pop_count.index[x][0]
)
&
(
population['sex'] == pop_count.index[x][1]
)
&
(
population['age'] == pop_count.index[x][2]
)
].sample(frac=0.001), range(len(pop_count))))
stratified_sample = pd.concat(stratified_sample)