影刀RPA 数据抽样与随机选取作者林焱什么情况用什么数据量太大需要抽样分析、随机抽取N条记录做测试、从客户名单中随机选取中奖者、按比例分层抽样做质检。在影刀RPA里用pandas的sample函数可以轻松实现随机抽样还支持按权重抽样和分层抽样。适用场景数据抽样分析、随机抽查质检、抽奖活动、测试数据生成、大数据量快速预览。怎么做基础随机抽样拼多多店群自动化报活动上架importpandasaspd dfpd.read_excel(rC:\Data\orders.xlsx)# 随机抽取10条sample_10df.sample(n10)# 随机抽取10%sample_10pctdf.sample(frac0.1)# 随机抽取80%用于训练集traindf.sample(frac0.8)# 剩余20%作为测试集testdf.drop(train.index)# 可重复实验设置随机种子sampledf.sample(n10,random_state42)# 每次运行结果相同分层抽样defstratified_sample(df,stratum_col,nNone,fracNone): 分层抽样每个分组按比例抽样 stratum_col: 分层依据列 n: 每组抽取数量 frac: 每组抽取比例 samples[]forstratum_val,groupindf.groupby(stratum_col):ifnisnotNone:# 每组抽n条不足则全部取sample_nmin(n,len(group))sampledgroup.sample(nsample_n,random_state42)![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/aa4835310af54e61a78eb9fd92d8fb63.png#pic_center)eliffracisnotNone:sampledgroup.sample(fracfrac,random_state42)samples.append(sampled)resultpd.concat(samples).reset_index(dropTrue)returnresult# 使用每个地区抽5条stratifiedstratified_sample(df,stratum_col地区,n5)# 每个地区抽10%stratifiedstratified_sample(df,stratum_col地区,frac0.1)按权重抽样# 按权重抽样金额大的被抽中概率更高df[权重]df[金额]/df[金额].sum()# 金额占比作为权重weighted_sampledf.sample(n20,weights权重,random_state42)# 自定义权重# VIP客户被抽中的概率是普通客户的3倍df[权重]df[客户等级].map({VIP:3,普通:1})weighted_sampledf.sample(n20,weights权重,random_state42)随机选取应用场景# 1. 随机抽奖deflottery_draw(participants_file,winners_count,output_file):随机抽奖dfpd.read_excel(participants_file)# 确保有唯一标识if工号notindf.columns:df[序号]range(1,len(df)1)key_col序号else:key_col工号# 随机抽取winnersdf.sample(nwinners_count,random_stateNone)# 不设种子真随机winners[中奖等级][一等奖]*min(1,len(winners))\[二等奖]*min(3,max(0,len(winners)-1))\[三等奖]*max(0,len(winners)-4)winners.to_excel(output_file,indexFalse)print(f参与人数:{len(df)})print(f中奖人数:{len(winners)})print(f中奖率:{len(winners)/len(df)*100:.2f}%)![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/6e50f01bb05d4dc09f4fe5d8706dc076.png#pic_center)returnwinners# 2. 质检抽样defquality_check_sample(df,sample_rate0.05,stratify_colNone):质检抽样ifstratify_col:# 分层抽样samplestratified_sample(df,stratify_col,fracsample_rate)else:# 简单随机抽样sampledf.sample(fracsample_rate,random_state42)sample[抽样时间]pd.Timestamp.now()sample[抽样方式]分层抽样ifstratify_colelse随机抽样returnsample# 使用按地区分层抽5%做质检qa_samplequality_check_sample(df,sample_rate0.05,stratify_col地区)qa_sample.to_excel(rC:\Data\qa_sample.xlsx,indexFalse)数据快速预览defquick_preview(df,n5):快速预览大数据print(f总行数:{len(df)})print(f总列数:{len(df.columns)})print(f\n随机{n}条预览:)print(df.sample(nmin(n,len(df)),random_state42).to_string())print(f\n数值列统计:)print(df.describe().round(2))print(f\n分类列分布:)cat_colsdf.select_dtypes(include[object]).columnsforcolincat_cols[:3]:print(f\n{col}:)print(f{df[col].value_counts().head(5).to_dict()})# 使用dfpd.read_excel(rC:\Data\big_data.xlsx)# 10万行quick_preview(df,n5)影刀RPA抽样流程【读取Excel文件】→ 全量数据 【执行Python代码】→ 分层抽样 按地区分层每组抽10% 【写入Excel文件】→ 抽样结果 【输出信息】 ![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/8cc7d994fdc14862b4aa20042af898d2.png#pic_center) 总数: 10000 抽样: 1000 分组: 北京200, 上海180, 广州150...有什么坑坑1sample(n)超过总行数TEMU店群矩阵自动化运营核价报活动# 问题只有5行但要抽10行df.sample(n10)# ValueError: Cannot take a larger sample than population when replaceFalse# 解决1用replaceTrue允许重复抽样df.sample(n10,replaceTrue)# 有放回抽样![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/11fd49a27bc5473097be06d4b0f4a0a6.png#pic_center)# 解决2限制数量nmin(10,len(df))df.sample(nn)坑2随机种子影响可重复性# 问题每次运行结果不同无法复现df.sample(n10)# 每次不同# 解决设置random_statedf.sample(n10,random_state42)# 每次相同# 但注意不同pandas版本可能结果不同# 如果需要严格复现保存抽样结果到文件坑3分层抽样比例不均# 问题某组只有3条要抽10%结果抽0条group.sample(frac0.1)# 3 * 0.1 0.3 → 抽0条# 解决设最少抽1条defsafe_sample(group,frac,min_n1):nmax(min_n,int(len(group)*frac))returngroup.sample(nmin(n,len(group)),random_state42)![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/90246262acac4be1b395aeb8423a6711.png#pic_center)# 或用ceilimportmath nmath.ceil(len(group)*frac)# 向上取整坑4抽样后索引乱# 问题抽样后索引不连续sampledf.sample(n10)print(sample.index)# 可能是 3, 7, 15, 22...# 解决重置索引sampledf.sample(n10).reset_index(dropTrue)坑5权重抽样权重为0的记录永远抽不到# 问题金额为0的记录权重为0永远抽不到df[权重]df[金额]# 金额为0的权重为0# 解决给所有记录一个基础权重![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/f29ac15d17ee4ed6a26926f2197bd9a8.png#pic_center)![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/ed88dce26c404f1a8440ffd821292287.png#pic_center)df[权重]df[金额]0.01# 加一个很小的值# 或者分两步先按权重抽大部分再从剩余中随机补