Python Pandas groupby分组采样时如何向上取整获得目标样本行数
Pandas分组采样按比例向上取整实现方案
pandas的DataFrame.sample()方法使用frac参数指定采样比例时,默认对计算出的采样行数做截断取整,若需要向上取整采样行数,可手动计算每组采样数量后传入n参数实现。
修改后代码如下:
import math grouped = df.groupby('EmployeeID') # 按10%比例向上取整计算每组采样行数 temp = grouped.apply(lambda x: x.sample(n=math.ceil(len(x) * 0.1))).reset_index(drop=True)
效果验证
- 场景1:EmployeeID为1的分组共15行,
15*0.1=1.5,向上取整后采样2行,和原有逻辑结果一致 - 场景2:EmployeeID为2的分组共12行,
12*0.1=1.2,向上取整后采样2行,符合需求
可选优化
如果存在空分组的情况,可增加判断避免报错:
temp = grouped.apply( lambda x: x.sample(n=math.ceil(len(x) * 0.1)) if len(x) > 0 else x ).reset_index(drop=True)
内容的提问来源于stack exchange,提问作者John Temple
相关产品推荐
相关产品推荐

