如何从大型轨迹数据集中高效筛选矩形区域内的数据
问题:高效筛选旋转矩形内的轨迹点并完成坐标变换
场景说明
我有一个包含多组轨迹坐标(X,Y)的DataFrame,实际为三组轨迹,先从一组开始处理。以下是可复现的示例代码:
import numpy as np import pandas as pd import plotly.graph_objects as go # 创建轨迹数据 n_points = 500 theta = np.linspace(0, 2 * np.pi, n_points) data = pd.DataFrame({ 'X': [10 * np.cos(theta) for theta in np.linspace(0, 2 * np.pi, n_points)], 'Y': [10 * np.sin(theta) for theta in np.linspace(0, 2 * np.pi, n_points)], 'XL': [11 * np.cos(theta) for theta in np.linspace(0, 2 * np.pi, n_points)], 'YL': [11 * np.sin(theta) for theta in np.linspace(0, 2 * np.pi, n_points)], 'XR': [9 * np.cos(theta) for theta in np.linspace(0, 2 * np.pi, n_points)], 'YR': [9 * np.sin(theta) for theta in np.linspace(0, 2 * np.pi, n_points)] }) fig = go.Figure() # 添加轨迹曲线 fig.add_trace(go.Scatter(x=data['X'], y=data['Y'], mode='lines+markers', name='Circle 1', line=dict(color='blue'))) fig.add_trace(go.Scatter(x=data['XL'], y=data['YL'], mode='lines+markers', name='Circle 2', line=dict(color='red'))) fig.add_trace(go.Scatter(x=data['XR'], y=data['YR'], mode='lines+markers', name='Circle 3', line=dict(color='green'))) # 定义矩形参数 XC, YC = 7.07, 7.07 # 矩形中心(位于X,Y轨迹上) XD, YD = 1, -1 # 矩形方向向量 width = 3 # 矩形宽度 height = 4 # 矩形高度 # 用三角函数计算矩形顶点坐标 theta = np.arctan2(YD, XD) cos_theta = np.cos(theta) sin_theta = np.sin(theta) rectangle_x = [XC + 0.5 * width * cos_theta - 0.5 * height * sin_theta, XC - 0.5 * width * cos_theta - 0.5 * height * sin_theta, XC - 0.5 * width * cos_theta + 0.5 * height * sin_theta, XC + 0.5 * width * cos_theta + 0.5 * height * sin_theta, XC + 0.5 * width * cos_theta - 0.5 * height * sin_theta] rectangle_y = [YC + 0.5 * width * sin_theta + 0.5 * height * cos_theta, YC - 0.5 * width * sin_theta + 0.5 * height * cos_theta, YC - 0.5 * width * sin_theta - 0.5 * height * cos_theta, YC + 0.5 * width * sin_theta - 0.5 * height * cos_theta, YC + 0.5 * width * sin_theta + 0.5 * height * cos_theta] # 添加矩形曲线 fig.add_trace(go.Scatter(x=rectangle_x, y=rectangle_y, fill='toself', name='Rectangle')) # 自定义布局 fig.update_layout( title='轨迹与矩形可视化', xaxis_title='X轴', yaxis_title='Y轴', showlegend=True ) # 设置坐标轴比例,确保圆形显示为正圆 fig.update_xaxes(scaleanchor="y", scaleratio=1) fig.update_yaxes(scaleanchor="x", scaleratio=1) fig.show()
上述代码会生成包含三个圆形轨迹和一个旋转矩形的可视化图,示例中用的是完美圆形轨迹,实际场景中轨迹可以是任意连续曲线。
需求说明
图中的矩形以X,Y轨迹上的点(XC,YC)为中心,我需要:
- 高效筛选出所有位于该矩形内的轨迹点,返回子DataFrame并可视化验证
- 已知可以遍历所有点判断是否在矩形内,但实际轨迹点可能多达50000个,遍历效率太低,需要更高效的方法
- 补充:筛选完成后,需要进行坐标变换——将(XC,YC)设为原点,让矩形的边与X/Y轴平行,再进行绘图,不过需要先完成筛选步骤
内容的提问来源于stack exchange,提问作者KansaiRobot
相关产品推荐
相关产品推荐

