Excel坐标筛选:Python实现两点距离小于三的坐标组提取
Excel坐标筛选:Python实现两点距离小于三的坐标组提取
本文将介绍如何使用Python筛选Excel中两点之间距离小于三的坐标组,并提供包含名称信息的完整解决方案。
需求背景:
假设我们有一份Excel文件,其中包含多个坐标点的名称、横坐标和纵坐标信息。我们需要从中筛选出所有两点之间距离小于三的坐标组,并保留每个点的名称信息。
**Python实现:**pythonimport pandas as pdimport math
读取Excel文件中的数据df_coordinates = pd.read_excel('坐标数据.xlsx')
创建空列表存储符合条件的坐标组coordinate_groups = []
遍历坐标点,寻找满足条件的坐标组for i in range(len(df_coordinates)): x1, y1 = df_coordinates.iloc[i]['X'], df_coordinates.iloc[i]['Y'] name1 = df_coordinates.iloc[i]['名称'] for j in range(i+1, len(df_coordinates)): x2, y2 = df_coordinates.iloc[j]['X'], df_coordinates.iloc[j]['Y'] name2 = df_coordinates.iloc[j]['名称'] distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) if distance < 3: coordinate_groups.append({'名称1': name1, '坐标1': (x1, y1), '名称2': name2, '坐标2': (x2, y2)})
打印符合条件的坐标组for group in coordinate_groups: print(group)
代码解读:
-
导入必要的库: -
pandas用于读取和处理Excel数据。 -math用于计算距离。 -
读取Excel数据: - 使用
pd.read_excel()函数读取Excel文件中的坐标数据,假设文件名为'坐标数据.xlsx'。 - 假设Excel文件中包含三列:'名称'、'X'和'Y',分别表示坐标点的名称、横坐标和纵坐标。 -
创建存储结果的列表: - 创建一个名为
coordinate_groups的空列表,用于存储所有符合条件的坐标组。 -
遍历坐标点: - 使用两个嵌套的
for循环遍历所有坐标点。 - 外层循环遍历每个坐标点作为第一个点。 - 内层循环遍历剩余的坐标点作为第二个点,避免重复计算。 -
计算距离: - 使用
math.sqrt((x2 - x1)**2 + (y2 - y1)**2)公式计算两个坐标点之间的距离。 -
筛选符合条件的坐标组: - 如果计算出的距离小于3,则将这两个坐标点及其对应的名称作为一个字典添加到
coordinate_groups列表中。 -
打印结果: - 使用
for循环遍历coordinate_groups列表,并打印每个符合条件的坐标组。
使用方法:
- 将代码保存为Python文件(例如
coordinate_filter.py)。2. 将示例代码中的'坐标数据.xlsx'替换为你的Excel文件路径。3. 根据实际情况调整列名和数据位置。4. 在命令行中运行代码:python coordinate_filter.py。
运行代码后,你将得到所有两点之间距离小于三的坐标组,每个坐标组都包含名称信息。
原文地址: https://www.cveoy.top/t/topic/PQT 著作权归作者所有。请勿转载和采集!