我有 2 组地理代码作为 pandas 系列,我正在尝试找到最快的方法来获得集合 A 中的点与集合 B 中的点的最小欧氏距离。 即:第二组中最接近 40.748043 和 -73.992953 的点,依此类推。 非常感谢任何建议/帮助。
Set A:
print(latitude1)
print(longitude1)
0 40.748043
1 42.361016
Name: latitude, dtype: float64
0 -73.992953
1 -71.020005
Name: longitude, dtype: float64
Set B:
print(latitude2)
print(longitude2)
0 42.50729
1 42.50779
2 25.56473
3 25.78953
4 25.33132
5 25.06570
6 25.59246
7 25.61955
8 25.33737
9 24.11028
Name: latitude, dtype: float64
0 1.53414
1 1.52109
2 55.55517
3 55.94320
4 56.34199
5 55.17128
6 56.26176
7 56.27291
8 55.41206
9 52.73056
Name: longitude, dtype: float64
最佳答案
这是一种只使用 numpy.linalg.norm
的方法.
import pandas as pd, numpy as np
df1['coords1'] = list(zip(df1['latitude1'], df1['longitude1']))
df2['coords2'] = list(zip(df2['latitude2'], df2['longitude2']))
def calc_min(x):
amin = np.argmin([np.linalg.norm(np.array(x)-np.array(y)) for y in df2['coords2']])
return df2['coords2'].iloc[amin]
df1['closest'] = df1['coords1'].map(calc_min)
# latitude1 longitude1 coords1 closest
# 0 40.748043 -73.992953 (40.748043, -73.992953) (42.50779, 1.52109)
# 1 42.361016 -71.020005 (42.361016, -71.020005) (42.50779, 1.52109)
# 2 25.361016 54.000000 (25.361016, 54.0) (25.0657, 55.17128)
设置
from io import StringIO
mystr1 = """latitude1|longitude1
40.748043|-73.992953
42.361016|-71.020005
25.361016|54.0000
"""
mystr2 = """latitude2|longitude2
42.50729|1.53414
42.50779|1.52109
25.56473|55.55517
25.78953|55.94320
25.33132|56.34199
25.06570|55.17128
25.59246|56.26176
25.61955|56.27291
25.33737|55.41206
24.11028|52.73056"""
df1 = pd.read_csv(StringIO(mystr1), sep='|')
df2 = pd.read_csv(StringIO(mystr2), sep='|')
如果性能是个问题,您可以通过底层的 numpy 数组相当轻松地向量化此计算。
关于python - 使用 numpy 查找最近的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49323171/