python - 德莱尼三角剖分的欧几里德距离 - Scipy

标签 python pandas scipy delaunay

spatialScipy 导入的包可以测量指定点之间的欧几里得距离。是否可以使用 Delaunay 返回相同的测量值?包裹?使用 df下面,所有点之间的平均距离按 Time 分组测量.但是,我希望使用 Delaunay 三角测量来测量平均距离。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay

df = pd.DataFrame({
    'Time' : [1,1,1,1,2,2,2,2],                  
    'A_X' : [5, 5, 6, 6, 4, 3, 3, 4], 
    'A_Y' : [5, 6, 6, 5, 5, 6, 5, 6],                         
        })

def make_points(x):
    return np.array(list(zip(x['A_X'], x['A_Y'])))

points = df.groupby("Time").apply(make_points)

for p in points:
    tri = Delaunay(p)
    ax.triplot(*p.T, tri.simplices)
之间的平均距离全部 可以使用下面的方法来衡量分数,但我希望加入德劳内。
 avg_dist = (df.groupby(['Time'])
             .apply(lambda x: spatial.distance.pdist
             (np.array(list(zip(x['A_X'], x['A_Y']))))
             .mean() if len(x) > 1 else 0)
             .reset_index()
             )
预期输出:
   Time         0
0     1  1.082842
1     2  1.082842

最佳答案

你可以试试这个功能

from itertools import combinations
import numpy as np
    
def edges_with_no_replacement(points):
    
    # get the unique coordinates
    points = np.unique(points.loc[:,['A_X','A_Y']].values,return_index=False,axis=0)
    if len(points) <= 1: return 0
    # for two points, no triangle
    # I think return the distance between the two points make more sense? You can change the return value to zero.
    if len(points) == 2: return np.linalg.norm(points[0]-points[1])
    
    tri = Delaunay(points)
    triangles = tri.simplices
    # get all the unique edges 
    all_edges = set([tuple(sorted(edge)) for item in triangles for edge in combinations(item,2)])
    # compute the average dist 
    return np.mean([np.linalg.norm(points[edge[0]]-points[edge[1]]) for edge in all_edges])
该函数将首先找到给定三角形的所有唯一边,然后返回三角形边的平均长度。应用此功能
avg_dist = (df.groupby(['Time']).apply(edges_with_no_replacement).reset_index())
输出是
    Time    0
0   1   1.082843
1   2   1.082843

注意函数edges_with_no_replacement还是会扔QhullError如果点在同一条线上,例如
Delaunay(np.array([[1,2],[1,3],[1,4]]))
所以,你必须确保这些点不在同一条线上。

关于python - 德莱尼三角剖分的欧几里德距离 - Scipy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64530316/

相关文章:

python - 没有名为 '_pywrap_tensorflow_internal' 的模块(仍然没有工作解决方案)

python - 具有 L-BFGS-B 方法 maxiter 属性的 scipy.optimize.minimize 函数不起作用

python - 如何在 Python 中对数字进行分类和分类?

opencv - 如何从一维子阵列中选择白色像素最少和最大的子阵列?

python - 根据条件修改值

python - 从 flask.ext.login 导入 LoginManager 时出现问题

python - ValueError:系列的真值不明确(API NaN 处理)

python - 在 .xlsx 文件中,如何插入一列,并将其从单元格 A2 填充到最大行?

python - 如何处理 Python XML-RPC 输出和异常?

python - 操作groupby对象