如何高效对DataFrame列按深度间隔分组求均值?
问题描述
我有一个包含10000列的DataFrame,列名为深度类数值,每一列对应一个深度值。希望通过增大列间隔,将10000列合并为5000列,具体需求如下:
- 基于新的深度间隔(示例中
spacing_new=2)生成分组中心列表(如[1.0, 3.0]) - 每个分组中心对应一个新列,新列的值是原DataFrame中列名落在
[分组中心 - 间隔/2, 分组中心 + 间隔/2]区间内的所有列的均值 - 原代码使用双重循环,处理10000列时耗时过长,寻求更优方案
演示示例:
import pandas as pd import numpy as np df = pd.DataFrame({'1':[1,2,3,4],'2.1':[2,4,6,8],'3.2':[3,6,9,12],'4.3':[4,8,12,16]}) df.columns = df.columns.astype('float') depth_list = df.columns.tolist() spacing_new = 2 depth_list_grouped = [x for x in np.arange(depth_list[0], depth_list[-1], step=spacing_new)] # depth_list_grouped 结果:[1.0, 3.0]
期望输出:
| 1.0 | 3.0 | |
|---|---|---|
| 0 | 1.5 | 3.0 |
| 1 | 3.0 | 6.0 |
| 2 | 4.5 | 9.0 |
| 3 | 6.0 | 12.0 |
原低效代码:
df_grouped = pd.DataFrame() for col_new in depth_list_grouped: df_grouped[col_new] = [0]*len(df) count = 0 for col in df.columns: if (col >= col_new - spacing_new/2) & ((col <= col_new + spacing_new/2)): df_grouped[col_new] += df[col] count += 1 df_grouped[col_new] = df_grouped[col_new]/count
优化方案
核心思路:用向量化操作替代双重循环
利用numpy.digitize快速给每列分配分组标签,再通过pandas的分组均值操作完成计算,全程避免循环,处理大规模列时效率提升显著。
代码实现
import pandas as pd import numpy as np # 初始化数据(替换为你的10000列DataFrame即可) df = pd.DataFrame({'1':[1,2,3,4],'2.1':[2,4,6,8],'3.2':[3,6,9,12],'4.3':[4,8,12,16]}) df.columns = df.columns.astype('float') depth_list = df.columns.tolist() spacing_new = 2 depth_list_grouped = np.arange(depth_list[0], depth_list[-1], step=spacing_new) # 生成分组区间边界:左边界为分组中心减间隔一半,追加右边界确保覆盖所有列 bin_edges = np.append(depth_list_grouped - spacing_new/2, depth_list_grouped[-1] + spacing_new/2) # 给每个原列分配对应的分组索引(转为0-based) group_indices = np.digitize(df.columns, bin_edges) - 1 # 按分组索引对列分组求均值,并重命名列 df_grouped = df.groupby(group_indices, axis=1).mean() df_grouped.columns = depth_list_grouped print(df_grouped)
为什么高效?
np.digitize:O(n)时间复杂度完成列的分组映射,比双重循环的O(n*m)快几个数量级groupby(axis=1).mean():pandas的分组操作基于C实现,向量化计算,处理10000列毫无压力- 全程无显式循环,完全利用库的优化能力,避免Python循环的性能损耗
适配10000列场景
无需修改代码,直接替换示例中的df为你的大数据集即可。该方案的耗时随列数线性增长,而非指数增长,能快速完成合并需求。
内容的提问来源于stack exchange,提问作者roudan
相关产品推荐
相关产品推荐

