获取坐标对数据框中目标坐标对所在的行号
获取edges数据框中指定坐标对所在的行号
假设我们有一个名为edges的DataFrame,每一行对应一条从(x0,y0)到(x1,y1)的边,数据如下:
| 行号 | x0 | y0 | x1 | y1 |
|---|---|---|---|---|
| 1 | 2.464286 | 2.464286 | 2.583333 | 1.750000 |
| 2 | 0.700000 | 3.787500 | 2.464286 | 2.464286 |
| 3 | 2.464286 | 2.464286 | 3.500000 | 3.500000 |
| 4 | 3.500000 | 3.500000 | 4.300000 | 3.900000 |
| 5 | 2.250000 | 4.750000 | 3.500000 | 3.500000 |
要找到包含指定坐标对的行号,这里有几种实用的方法,根据你的场景选择:
方法1:精确匹配(适合整数/无精度问题的浮点数)
如果你的坐标值是完全精确的(比如示例里的数值没有存储误差),直接用布尔索引筛选就行。比如我们要找起点(2.464286, 2.464286)、终点(3.500000, 3.500000)的边:
import pandas as pd # 先构造示例数据框(行号从1开始,和你的示例一致) edges = pd.DataFrame({ 'x0': [2.464286, 0.700000, 2.464286, 3.500000, 2.250000], 'y0': [2.464286, 3.787500, 2.464286, 3.500000, 4.750000], 'x1': [2.583333, 2.464286, 3.500000, 4.300000, 3.500000], 'y1': [1.750000, 2.464286, 3.500000, 3.900000, 3.500000] }, index=range(1,6)) # 定义要匹配的目标坐标 target_x0, target_y0 = 2.464286, 2.464286 target_x1, target_y1 = 3.500000, 3.500000 # 筛选符合条件的行 matches = edges[(edges['x0'] == target_x0) & (edges['y0'] == target_y0) & (edges['x1'] == target_x1) & (edges['y1'] == target_y1)] # 提取行号 row_ids = matches.index.tolist() print(row_ids) # 输出: [3]
方法2:近似匹配(解决浮点数精度坑)
浮点数在存储时经常会有微小误差(比如2.464286实际可能存成2.464285999999999),这时候直接用==会匹配失败。推荐用numpy.isclose来做近似匹配:
import numpy as np # 用近似匹配替代精确相等 matches = edges[np.isclose(edges['x0'], target_x0) & np.isclose(edges['y0'], target_y0) & np.isclose(edges['x1'], target_x1) & np.isclose(edges['y1'], target_y1)] row_ids = matches.index.tolist() print(row_ids) # 依然输出: [3]
你还可以通过rtol和atol参数调整匹配的精度阈值,比如np.isclose(a, b, rtol=1e-5, atol=1e-8),按需设置就行。
方法3:用query简化代码
如果觉得布尔索引写起来太长,可以用pandas的query方法,代码更简洁:
# 精确匹配的query写法 matches = edges.query(f"x0 == {target_x0} and y0 == {target_y0} and x1 == {target_x1} and y1 == {target_y1}") # 近似匹配的query写法(需要引入numpy) matches = edges.query(f"np.isclose(x0, {target_x0}) and np.isclose(y0, {target_y0}) and np.isclose(x1, {target_x1}) and np.isclose(y1, {target_y1})") row_ids = matches.index.tolist()
额外补充:匹配无向边(可选)
如果你的场景中边是无向的(比如A→B和B→A算同一条边),可以同时匹配两种方向:
matches = edges[ # 匹配A→B ((np.isclose(edges['x0'], target_x0) & np.isclose(edges['y0'], target_y0)) & (np.isclose(edges['x1'], target_x1) & np.isclose(edges['y1'], target_y1))) | # 匹配B→A ((np.isclose(edges['x0'], target_x1) & np.isclose(edges['y0'], target_y1)) & (np.isclose(edges['x1'], target_x0) & np.isclose(edges['y1'], target_y0))) ]
内容的提问来源于stack exchange,提问作者QLG
相关产品推荐
相关产品推荐

