问题描述
我有一个数据框,我想对其采样。但是,在随机采样时,我希望列中的每个元素至少有1个采样。我也希望分布也有效果。(例如:原始样本上包含更多样本的值在样本df上具有更多
让我们说这是我的df:
df = pd.DataFrame(columns=['class'])
df['class'] = [0,1,2]
df_sample = df.sample(n=4)
当我对此采样时,我希望df_sample看起来像:
Class
0
0
1
2
谢谢。
解决方法
根据@YukiShioriii的建议,您可以:
1-对每组值的一行进行采样
2-随机采样剩余的行,而不考虑值
,遵循YukiShioriii和mprouveur的建议
request.auth.token.nameOfTheListField.hasAny(groupIds)
输出
# random_state for reproducibility,remove in production code
sample = df.groupby('class').sample(1,random_state=1)
sample = sample.append(
df[~df.index.isin(sample.index)] # only rows that have not been selected
.sample(n=sample_size-sample.shape[0]) # sample more rows as needed
).sort_index()