我有这样的表格:
我尝试从
import pandas as pd
import numpy as np
df1 = pd.DataFrame([
['A', (37.55, 126.97)],
['B', (37.56, 126.97)],
['C', (37.57, 126.98)]
], columns=['STA_NM', 'COORD'])
df2 = pd.DataFrame([
['A-01', (37.57, 126.99)]
], columns=['ID', 'COORD'])
我尝试从
df2
中挑选每个坐标,并找到距离df1
中每个坐标最近的两个站点(STA_NM
),然后将它们及其与每个坐标的距离添加到df2
的一个新列中。我尝试了以下代码:from heapq import nsmallest
from math import cos, asin, sqrt
def dist(x, y):
p = 0.017453292519943295
a = 0.5 - cos((y[0] - x[0]) * p) / 2 + cos(x[0] * p) * cos(y[0] * p) * (1 - cos((y[1] - x[1]) * p)) / 2
return 12741 * asin(sqrt(a))
def shortest(df, v):
l_sta = []
# get a list of coords
l_coord = df['COORD'].tolist()
# get the two nearest coordinates
near_coord = nsmallest(2, l_coord, key=lambda p: dist(v, p))
# find station names
l_sta.append((df.loc[df['COORD'] == near_coord[0], 'STA_NM'].to_string(index=False), round(dist(near_coord[0], v) * 1000)))
l_sta.append((df.loc[df['COORD'] == near_coord[1], 'STA_NM'].to_string(index=False), round(dist(near_coord[1], v) * 1000)))
# e.g.: [('A', 700), ('B', 1000)]
return l_sta
df2['NEAR_STA'] = df2['COORD'].map(lambda x: shortest(df1, x))
原始数据中,df1
大约有700行,df2
大约有55000行。当我尝试上述代码时,执行时间接近两分钟。有没有更好的方法让它运行更快?
scipy.spatial.KDTree
。 - Aaron Keesing