如何计算三维空间中点的距离?(Python实现)
三维点按Y轴区间分组计算距离总和的实现方案
一、你的原始思路实现
假设你有三个一维数组x、y、z,每个数组长度相同,对应一组三维点的坐标。以下是按Y轴划分区间、排序后计算相邻点距离总和的具体步骤:
步骤1:数据准备与分组
先将三个数组合并为三维点数组,再定义Y轴划分区间,把点分配到对应区间中:
import numpy as np # 替换为你的真实数据 x = np.array([1, 2, 3, 4, 5, 6]) y = np.array([0.5, 1.2, 1.8, 2.3, 2.7, 3.5]) z = np.array([2, 3, 1, 4, 2, 5]) # 合并为三维点数组,shape为(n, 3) points = np.column_stack((x, y, z)) # 定义Y轴划分区间,示例为[0,1), [1,2), [2,3), [3,4) y_bins = np.arange(0, 4, 1) # 获取每个点所属的区间索引 point_bin_indices = np.digitize(points[:, 1], y_bins)
步骤2:按区间处理,计算相邻点距离总和
遍历每个区间,取出对应点并按Y值排序,计算相邻点的三维距离后累加:
total_distance = 0.0 # 遍历所有区间(digitize返回的索引从1开始,对应y_bins的区间) for bin_idx in range(1, len(y_bins)): bin_points = points[point_bin_indices == bin_idx] if len(bin_points) < 2: continue # 少于2个点无法计算线段长度,直接跳过 # 按Y值(第二列)从小到大排序 sorted_points = bin_points[np.argsort(bin_points[:, 1])] # 计算相邻点的欧氏距离 diffs = sorted_points[1:] - sorted_points[:-1] segment_lengths = np.sqrt(np.sum(diffs**2, axis=1)) # 累加当前区间的线段长度总和 total_distance += np.sum(segment_lengths) print("总距离:", total_distance)
二、其他计算方案
方案1:计算区间内所有点对的距离总和
如果需要统计区间内所有点对之间的距离总和(而非相邻点),可以结合scipy的pdist工具实现:
from scipy.spatial.distance import pdist total_pair_distance = 0.0 for bin_idx in range(1, len(y_bins)): bin_points = points[point_bin_indices == bin_idx] if len(bin_points) < 2: continue # 计算当前区间内所有点对的距离并求和 distances = pdist(bin_points) total_pair_distance += np.sum(distances) print("所有点对总距离:", total_pair_distance)
方案2:向量化优化(适用于大规模数据)
如果点数量较大,循环遍历区间效率较低,可采用numpy向量化操作优化:
# 先按Y值整体排序所有点 sorted_all = points[np.argsort(points[:, 1])] # 按Y轴区间分割已排序的点数组 split_points = np.split(sorted_all, np.digitize(sorted_all[:, 1], y_bins)[1:-1]) total_vec_distance = 0.0 for part in split_points: if len(part) < 2: continue diffs = part[1:] - part[:-1] total_vec_distance += np.sum(np.sqrt(np.sum(diffs**2, axis=1))) print("向量化计算总距离:", total_vec_distance)
内容的提问来源于stack exchange,提问作者lainri
相关产品推荐
相关产品推荐

