[英]sampling dataframe based on quantile (pandas)
我有一个数据框,我想根据参数num_samples
对其进行采样。 我想基于年龄跨分位数统一采样。
例如,如果我的 dataframe 有 1000 行且num_samples =.5
,我将需要采样 500 行,但每个分位数为 125。
我的 dataframe 的前几条记录是这样的:
Age x1 x2 x3
12 1 1 2
45 2 1 3
67 4 1 2
11 3 4 10
18 9 7 6
45 3 5 8
78 8 4 7
64 6 2 3
33 3 2 2
我怎样才能在 python/pandas 中做到这一点?
创建一个列分位数,其中包含Age1
的bin
。 然后使用 boolean 掩蔽和重新采样以从每个 bin 中采样,使用pd.concat
连接每个 bin 获得的样本。
labels = ['q1', 'q2', 'q3', 'q4']
df['quantile'] = pd.qcut(df.Age, q = 4, labels = labels)
out = pd.concat([df[df['quantile'].eq(label)].sample(1) for label in labels])
印刷:
>>> out
Age x1 x2 x3 quantile
4 18 9 7 6 q1
8 33 3 2 2 q2
7 64 6 2 3 q3
2 67 4 1 2 q4
PS 对于采样 n 个样本,将sample(1)
更改为sample(n)
。
从 Pandas 1.1.0 开始,有groupby().sample
所以你可以这样做:
df.groupby(pd.qcut(df.Age, duplicates='drop')).sample(frac=0.5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.