使用Pandas统计DataFrame中位于给定半径范围内的点位数量
实现代码(按要求使用索引遍历方式)
import pandas as pd # 定义参数和样例数据 radius = 3 df = pd.DataFrame({'spot_id':[1,2,3,4,5],'x_pos':[5,4,10,3,8],'y_pos':[4,10,8,6,3]}) # 初始化结果列 df['spots_within_radius'] = 0 # 两层遍历索引实现计数 for current_idx in df.index: # 获取当前点位坐标 curr_x = df.loc[current_idx, 'x_pos'] curr_y = df.loc[current_idx, 'y_pos'] within_count = 0 for compare_idx in df.index: # 跳过自身点位 if current_idx == compare_idx: continue # 计算距离平方(避免开根号提升效率,判断逻辑和直接对比距离一致) dist_square = (curr_x - df.loc[compare_idx, 'x_pos'])**2 + (curr_y - df.loc[compare_idx, 'y_pos'])**2 if dist_square <= radius**2: within_count += 1 # 写入当前点位的统计结果 df.loc[current_idx, 'spots_within_radius'] = within_count print(df)
输出结果
运行上述代码后得到的df和你要求的结果完全一致:
spot_id x_pos y_pos spots_within_radius 0 1 5 4 1 1 2 4 10 0 2 3 10 8 0 3 4 3 6 1 4 5 8 3 0
补充优化建议
如果后续数据量较大,两层遍历的时间复杂度为O(n²)效率较低,可以替换为向量化计算方案,不需要修改核心逻辑就能大幅提升运行速度。
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

