[英]Fastest way to calculate the shortest (euclidean) distance between points, in pandas dataframe
[英]How calculate euclidean distance between pandas and list?
我有一个熊猫数据框,我尝试用固定值计算所有欧几里德距离并找到最短距离。
我的数据框“货币”:
Stype h line ... y y2 bc
45 currency 38 13 ... 1344 1382 (1731.0, 1363.0)
46 currency 38 13 ... 1343 1381 (2015.0, 1362.0)
47 currency 39 13 ... 1342 1381 (2267.5, 1361.5)
60 currency 39 15 ... 2718 2757 (488.0, 2737.5)
61 currency 39 15 ... 2717 2756 (813.5, 2736.5)
62 currency 39 15 ... 2718 2757 (1332.5, 2737.5)
63 currency 40 15 ... 2716 2756 (1821.5, 2736.0)
64 currency 39 15 ... 2715 2754 (2286.5, 2734.5)
68 currency 39 17 ... 2874 2913 (2287.5, 2893.5)
162 currency 30 22 ... 3311 3341 (1104.5, 3326.0)
我的列表中的示例值 [l['bc']]
[(2126.5, 2657.0)]
我的代码:
for l in label_dic:
print('bc:', [l['bc']])
print(cdist([l['bc']], currency.bc.values, 'euclidean'))
我的问题:
ValueError: XB must be a 2-dimensional array.
我已经验证了我的功能:
print(cdist([l['bc']], [l['bc']], 'euclidean'))
Result: [[0.]]
你能解释我如何解决它吗?
谢谢
currency.bc.values 似乎给出了一个一维 numpy 元组数组,但 cdist 需要一个二维 numpy 数组。 您可以使用 np.array([*currency.bc.values]) 将其转换为二维数组
看下面的例子
from scipy.spatial import distance
import pandas as pd
import numpy as np
mypoint = [(0, 0)]
df = pd.DataFrame({'coord1': [(0,10), (10,0)]})
#option 1
print(distance.cdist(mypoint , np.array([*df.coord1.values]), 'euclidean'))
#option2
print(distance.cdist(mypoint , df.coord1.values.tolist(), 'euclidean'))
结果是
[[10. 10.]]
[[10. 10.]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.