基于分位数的采样数据帧(panda)



我有一个数据帧,我想基于参数num_samples对其进行采样。我想根据年龄在分位数之间进行统一采样。

例如,如果我的数据帧有1000行,num_samples = .5,我需要对500行进行采样,但每个分位数要采样125行。

我的数据帧的前几条记录如下:

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

我如何在蟒蛇/熊猫身上做到这一点?

Age1创建一个具有bin的列分位数。然后使用布尔掩码和重采样从每个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

p.S.对于采样n个样本,请将sample(1)更改为sample(n)

从Pandas 1.1.0,有groupby().sample,所以你可以做这样的事情:

df.groupby(pd.qcut(df.Age, duplicates='drop')).sample(frac=0.5)