我有一个 pandas 数据框,我尝试计算具有固定值的所有欧几里德距离并找到最短距离。
我的数据框“货币”:
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 似乎给出了一个 1d numpy 元组数组,但 cdist 需要一个 2d 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.]]
关于python - 如何计算pandas和list之间的欧氏距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54261451/