I am trying to sample data from a big dataset.
The dataset is like
id label
1 A
2 B
3 C
4 A
.........
Code to generate a sample dataset
labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']
df = pd.DataFrame()
N = 300000
weights = [0.350019, 0.209966, 0.126553, 0.100983, 0.053767, 0.039378, 0.029529,
0.019056, 0.016783, 0.014813, 0.014152, 0.013477, 0.009444, 0.002082]
import random
df['id'] = list(range(1, N+1))
df['label'] = list(random.choices(labels, weights=weights, k=N))
group_dict= df.groupby(['id']).apply(lambda x: list(set(x['label'].tolist()))[0]).to_dict()
df = pd.DataFrame(group_dict.items())
df.columns= ['id','label']
The distribution of labels in the dataset is
df['label'].value_counts(normalize=True)
A 0.350373
B 0.209707
C 0.126307
D 0.101353
E 0.053917
F 0.039487
G 0.029217
H 0.018780
I 0.016510
J 0.015083
K 0.014323
L 0.013467
M 0.009530
N 0.001947
I created a new column in the dataset
df['freq'] = df.groupby('label')['label'].transform('count')
When I am trying to sample say 5000 items
sampledf = df.sample(n=5000, weights=df.freq,
random_state=42)
The distribution of the labels in the sampledf is not same as that in the df
A 0.6048
B 0.2198
C 0.0850
D 0.0544
E 0.0190
F 0.0082
G 0.0038
H 0.0020
I 0.0010
K 0.0008
L 0.0008
J 0.0004
I am not sure why the distribution is not the same as the actual data frame.
Can anybody help me with what I am missing here?
Thanks