计算ATM的欧几里得距离

时间:2020-08-09 17:56:04

标签: python-3.x pandas-groupby euclidean-distance

enter image description here

我需要按库(clean_name)对atm进行分组,并计算特定库中每个atms的距离,并找到最大欧几里得距离。

不确定如何将欧几里得函数应用于groupby并输出最大欧几里得距离

2 个答案:

答案 0 :(得分:0)

欧几里得的计算公式如下(运行摘要):

<img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/4febdae84cbc320c19dd13eac5060a984fd438d8" class="mwe-math-fallback-image-inline" aria-hidden="true" style="vertical-align: -1.671ex; width:35.907ex; height:4.843ex;" alt="{\displaystyle d(\mathbf {p} ,\mathbf {q} )={\sqrt {(q_{1}-p_{1})^{2}+(q_{2}-p_{2})^{2}}}.}">

对银行名称(clean_name)进行排序,然后使用上述公式计算银行与自动柜员机之间的距离。

答案 1 :(得分:0)

所以我不确定这是否是您期望的结果。我生成了随机的ATM位置,并使用从ATM0到ATM100的随机ATM名称。

"""Test Values"""
import pandas as pd
import numpy as np

atms = {
    'clean_name' : ['ATM'+str(int(round(i*100))) for i in np.random.rand(300)],
    'x': np.random.rand(300)*100000,
    'y': np.random.rand(300)*100000
}
df = pd.DataFrame(atms)

我像您在评论中一样对银行进行了分组,并等待搜索到ATM的用户输入:

atm_df = df.groupby('clean_name') #Group

"""User-Interface"""
atms = atm_df.groups.keys() #Get all available atm names
atm_name = ''

while atm_name not in atms:
    atm_name = input()

used_atms = atm_df.get_group(atm_name)
print("Used-ATM: {}\nAvailables ATMS: {}".format(atm_name, len(used_atms)))

您需要插入ATM的名称。在我的(随机)示例中,输入为“ ATM10”,输出如下所示:

ATM10
Used-ATM: ATM10
Availables ATMS: 3

然后,我们需要获得欧几里得测量的起始位置(可以是x和y值的任何位置)

start_pos = {'x': 50000, 'y': 50000}

def euclidean(d_x, d_y, s_x, s_y): 
    return np.sqrt([(d_x-s_x)**2 + (d_y - s_y)**2]).tolist()[0] #euclidean distance function with destination (d) and start (s)

然后您计算距离并返回最大值

used_atms['distance'] = euclidean(used_atms['x'], used_atms['y'], start_pos['x'], start_pos['y'])
max_atm =  used_atms.loc[used_atms['distance'].idxmax()] #max-distance

如果要说明自动取款机,可以遵循以下源代码:

import matplotlib.pyplot as plt

#line from start to destination
lines_x = [start_pos['x'], max_atm['x']]
lines_y = [start_pos['y'], max_atm['y']]

fig, ax = plt.subplots()

#Plot all Datapoints
ax.scatter(df['x'], df['y'])
ax.scatter(start_pos['x'], start_pos['y'], color='r')
ax.scatter(used_atms['x'], used_atms['y'], color='cyan')

#Plot the line
ax.plot(lines_x, lines_y, color='r')
    
plt.show()
plt.savefig("atms.png")

结果如下:

enter image description here

进一步的问题。请更加准确,发布您的源代码(可重复使用,不能在注释中使用)