我将尝试解释我目前使用的是什么:我有两个数据帧:一个用于加油站A (165个加油站),另一个用于加油站B (257个加油站)。它们都使用相同的格式:
id Coor
1 (a1,b1)
2 (a2,b2)
Coor具有位置坐标的元组。我想做的是向Dataframe A添加3列,其中最接近的竞争对手#1、#2和#3 (来自加油站B)。目前,我设法获得了从A到B的每一个距离(42405个距离度量),但是是以列表的形式:
distances=[]
for (u,v) in gasA['coor']:
for (w,x) in gasB['coor']:
distances.append(sp.distance.euclidean((u,v),(w,x)))
这让我有了我需要的值,但我仍然需要将它们与加油站A的ID进行匹配,并获得前3名。我怀疑使用列表不是最好的方法。你有什么建议吗?
编辑:按照建议,前5行是:在GasA中:
id coor
60712 (-333525363206695,-705191013427772)
60512 (-333539879388388, -705394161580837)
60085 (-333545609177068, -703168832659184)
60110 (-333601677229216, -705167284798638)
60078 (-333608898397271, -707213099595404)
在GasB中:
id coor
70174 (-333427160000000,-705459060000000)
70223 (-333523030000000, -706705470000000)
70383 (-333549270000000, -705320990000000)
70162 (-333556960000000, -705384750000000)
70289 (-333565850000000, -705104360000000)
发布于 2018-07-13 03:38:11
from sklearn.metrics.pairwise import euclidean_distances
import numpy as np
创建数据:
A = pd.DataFrame({'id':['60712','60512','60085', '60110','60078'], 'coor':[ (-333525363206695,-705191013427772),\
(-333539879388388, -705394161580837),\
(-333545609177068, -703168832659184),\
(-333601677229216, -705167284798638),\
(-333608898397271, -707213099595404)]})
B = pd.DataFrame({'id':['70174','70223','70383', '70162','70289'], 'coor':[ (-333427160000000,-705459060000000),\
(-333523030000000, -706705470000000),\
(-333549270000000, -705320990000000),\
(-333556960000000, -705384750000000),\
(-333565850000000, -705104360000000)]})
计算距离:
res = euclidean_distances(list(A.coor), list(B.coor))
从B中选择最接近的3个桩号,并附加到A中的列:
d = []
for i, id_ in enumerate(A.index):
distances = np.argsort(res[i])[0:3] #select top 3
distances = B.iloc[distances]['id'].values
d.append(distances)
A = A.assign(dist=d)
编辑
示例运行结果:
coor id dist
0 (-333525363206695, -705191013427772) 60712 [70223, 70174, 70162]
1 (-333539879388388, -705394161580837) 60512 [70223, 70289, 70174]
2 (-333545609177068, -703168832659184) 60085 [70223, 70174, 70162]
3 (-333601677229216, -705167284798638) 60110 [70223, 70174, 70162]
4 (-333608898397271, -707213099595404) 60078 [70289, 70383, 70162]
发布于 2018-07-13 02:12:00
你可以这样做。
a = gasA.coor.values
b = gasB.coor.values
c = np.sum(np.sum((a[:,None,::-1] - b)**2, axis=1), axis=0)
我们可以得到两个坐标的numpy数组,然后广播a来表示它的所有组合,然后取欧几里得距离。
发布于 2018-07-13 02:23:18
定义一个函数来计算从A到所有B的距离,并返回具有三个最小距离的B的索引。
def get_nearest_three(row):
(u,v) = row['Coor']
dist_list = gasB.Coor.apply(sp.distance.euclidean,args = [u,v])
# want indices of the 3 indices of B with smallest distances
return list(np.argsort(dist_list))[0:3]
gasA['dists'] = gasA.apply(get_nearest_three, axis = 1)
https://stackoverflow.com/questions/51311894
复制相似问题