对含position列的DataFrame分箱并计算样本列平均值
对大样本数据按position分箱并计算各样本列均值
问题描述
我有一份包含position列和多列样本值的数据集,行数超过50000行。为绘制折线图,需要将数据划分为50个分箱(bins),并计算每个分箱内各样本列的平均值。
示例输入
position sample_1 sample_2 sample_3 sample_4 1001 21 43 28 35 1002 22 42 29 38 1003 23 46 23 42 1004 26 43 26 46 1005 31 31 31 43 1006 26 35 26 31 1007 18 36 24 35 1008 19 37 23 39 1009 21 34 22 23 1010 31 24 21 26 1011 32 23 20 31 1012 34 36 22 26 1013 25 43 23 25 1014 27 42 26 27 1015 26 46 26 26 1016 35 47 31 28
期望输出(分为4个分箱的结果)
Bin sample_1 sample_2 sample_3 sample_4 1001-1004 23 43.5 26.5 40.25 1005-1008 23.5 34.75 26 37 1009-1012 29.5 29.25 21.25 26.5 1013-1016 28.25 44.5 26.5 26.5
解决方案(Python pandas实现)
使用pandas可高效处理大样本数据的分箱与均值计算,代码如下:
import pandas as pd # 读取数据:实际场景可替换为pd.read_csv("your_data.csv")等方式 data = pd.DataFrame({ 'position': [1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016], 'sample_1': [21,22,23,26,31,26,18,19,21,31,32,34,25,27,26,35], 'sample_2': [43,42,46,43,31,35,36,37,34,24,23,36,43,42,46,47], 'sample_3': [28,29,23,26,31,26,24,23,22,21,20,22,23,26,26,31], 'sample_4': [35,38,42,46,43,31,35,39,23,26,31,26,25,27,26,28] }) # 对position列分箱:示例设为4个分箱,实际需求改为bins=50即可 bins = pd.cut(data['position'], bins=4, include_lowest=True) # 自定义分箱标签,格式为"起始值-结束值" bin_labels = [f"{int(bin.left)}-{int(bin.right)}" for bin in bins.cat.categories] bins = bins.cat.rename_categories(bin_labels) # 按分箱分组,计算各样本列的均值 result = data.groupby(bins).mean().reset_index() # 重命名分箱列为"Bin" result = result.rename(columns={'position': 'Bin'}) # 输出结果,自动保留合适的小数位数 print(result.to_string(index=False))
说明
- 50000行数据的分组计算,pandas的效率完全满足需求;
- 若需自定义分箱区间(而非均分),可将
bins参数改为自定义区间列表,例如bins=[1000, 2000, 3000, ...]; - 输出结果可通过
result.to_csv("binned_mean.csv")保存为文件,方便后续绘图使用。
内容的提问来源于stack exchange,提问作者roaring_panda
相关产品推荐
相关产品推荐

