如何用NumPy对(6000,2)数组做二维分箱统计及3D数组深度标准差计算
用NumPy实现二维分箱计数与三维分箱标准差计算
一、单个二维数组的10x10分箱计数
直接使用np.histogram2d即可高效完成统计,无需手动条件判断或依赖绘图工具。该函数会自动按指定范围和分箱数统计每个格子内的数据点数量:
import numpy as np # 生成测试数据(6000个二维坐标点) a = np.random.rand(6000, 2) # 计算0-1范围内10x10分箱的点数量 counts, x_edges, y_edges = np.histogram2d( a[:, 0], # x轴数据 a[:, 1], # y轴数据 bins=10, # 每个维度10个分箱 range=[[0, 1], [0, 1]] # 分箱范围 ) # counts即为10x10的结果数组,每个元素对应对应分箱内的点数 print(counts.shape) # 输出: (10, 10)
二、三维数组的分箱深度方向标准差
假设你的三维数组由多个(N,2)的二维点集堆叠而成,我们先对每个深度层的点集计算分箱计数,再沿深度维度计算每个分箱的标准差:
import numpy as np # 生成测试数据:2个深度层,每层6000个二维坐标点 a = np.random.rand(6000, 2) b = np.random.rand(6000, 2) # 按深度维度堆叠,shape变为(2, 6000, 2) brick = np.stack((a, b), axis=0) # 批量计算每个深度层的分箱计数 depth_counts = [] for layer in brick: layer_counts, _, _ = np.histogram2d( layer[:, 0], layer[:, 1], bins=10, range=[[0, 1], [0, 1]] ) depth_counts.append(layer_counts) # 转换为NumPy数组,shape为(深度层数, 10, 10) depth_counts = np.array(depth_counts) # 沿深度方向(axis=0)计算每个分箱的标准差 bin_std = np.std(depth_counts, axis=0) print(bin_std.shape) # 输出: (10, 10)
如果追求更高效率,可以用向量化操作替代循环,但对于常规深度层数来说,循环的可读性和性能已经足够。
内容的提问来源于stack exchange,提问作者Toto
相关产品推荐
相关产品推荐

