猿问

检查点是否在 circleS 内

我有一长串H-points已知坐标的列表。我还有一份清单TP-points。我想知道是否H-points落在TP-point具有一定半径(例如r=5)的任何(!)内。


dfPoints = pd.DataFrame({'H-points' : ['a','b','c','d','e'],

               'Xh' :[10, 35, 52, 78, 9],

               'Yh' : [15,5,11,20,10]})


dfTrafaPostaje = pd.DataFrame({'TP-points' : ['a','b','c','d','e'],

               'Xt' :[15,25,35],

               'Yt' : [15,25,35],

               'M' : [5,2,3]})


def inside_circle(x, y, a, b, r):

    return (x - a)*(x - a) + (y - b)*(y - b) < r*r

我已经开始了,但是.. 只检查一个 TP 点会容易得多。但是如果我有 1500 个和 30.000 个 H 点,那么我需要更通用的解决方案。任何人都可以帮忙吗?


慕雪6442864
浏览 75回答 2
2回答

紫衣仙女

另一种选择是使用distance_matrixfrom scipy.spatial:dist_mat = distance_matrix(dfPoints [['Xh','Yh']], dfTrafaPostaje [['Xt','Yt']])dfPoints [np.min(dist_mat,axis=1)<5]1500 dfPoints和花了大约 2 秒30000 dfTrafaPostje。更新:获取得分最高的参考点的索引:dist_mat = distance_matrix(dfPoints [['Xh','Yh']], dfTrafaPostaje [['Xt','Yt']])# get the M scores of those within rangeM_mat = pd.DataFrame(np.where(dist_mat <= 5, dfTrafaPosaje['M'].values[None, :], np.nan),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;index=dfPoints['H-points'] ,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;columns=dfTrafaPostaje['TP-points'])# get the points with largest M values# mask with np.nan for those outside range&nbsp; &nbsp;&nbsp;dfPoints['M'] = np.where(M_mat.notnull().any(1), M_mat.idxmax(1), np.nan)对于包含的样本数据:&nbsp; H-points&nbsp; Xh&nbsp; Yh&nbsp; &nbsp;TP0&nbsp; &nbsp; &nbsp; &nbsp; a&nbsp; 10&nbsp; 15&nbsp; &nbsp; a1&nbsp; &nbsp; &nbsp; &nbsp; b&nbsp; 35&nbsp; &nbsp;5&nbsp; NaN2&nbsp; &nbsp; &nbsp; &nbsp; c&nbsp; 52&nbsp; 11&nbsp; NaN3&nbsp; &nbsp; &nbsp; &nbsp; d&nbsp; 78&nbsp; 20&nbsp; NaN4&nbsp; &nbsp; &nbsp; &nbsp; e&nbsp; &nbsp;9&nbsp; 10&nbsp; NaN

慕虎7371278

您可以使用scipy中的 cdist 计算成对距离,然后在距离小于半径的地方创建一个带有 True 的掩码,最后过滤:import pandas as pdfrom scipy.spatial.distance import cdistdfPoints = pd.DataFrame({'H-points': ['a', 'b', 'c', 'd', 'e'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'Xh': [10, 35, 52, 78, 9],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'Yh': [15, 5, 11, 20, 10]})dfTrafaPostaje = pd.DataFrame({'TP-points': ['a', 'b', 'c'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'Xt': [15, 25, 35],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'Yt': [15, 25, 35]})radius = 5distances = cdist(dfPoints[['Xh', 'Yh']].values, dfTrafaPostaje[['Xt', 'Yt']].values, 'sqeuclidean')mask = (distances <= radius*radius).sum(axis=1) > 0 # create maskprint(dfPoints[mask])输出&nbsp; H-points&nbsp; Xh&nbsp; Yh0&nbsp; &nbsp; &nbsp; &nbsp; a&nbsp; 10&nbsp; 15
随时随地看视频慕课网APP

相关分类

Python
我要回答