我正在为大学的一个项目工作,其中有两个pandas数据框:
# Libraries
import pandas as pd
from geopy import distance
# Dataframes
df1 = pd.DataFrame({'id': [1,2,3],
'lat':[-23.48, -22.94, -23.22],
'long':[-46.36, -45.40, -45.80]})
df2 = pd.DataFrame({'id': [100,200,300],
'lat':[-28.48, -22.94, -23.22],
'long':[-46.36, -46.40, -45.80]})
我需要计算数据框中地理纬度和经度坐标之间的距离。因此我使用了geopy。如果坐标组合之间的距离小于100米的阈值,则必须在“nearby”列中赋值为1。我编写了以下代码:
threshold = 100 # meters
df1['nearby'] = 0
for i in range(0, len(df1)):
for j in range(0, len(df2)):
coord_geo_1 = (df1['lat'].iloc[i], df1['long'].iloc[i])
coord_geo_2 = (df2['lat'].iloc[j], df2['long'].iloc[j])
var_distance = (distance.distance(coord_geo_1, coord_geo_2).km) * 1000
if(var_distance < threshold):
df1['nearby'].iloc[i] = 1
虽然有警告出现,但代码仍在运行。不过我想找到一种方法来覆盖 for() 循环。这是可能的吗?
# Output:
id lat long nearby
1 -23.48 -46.36 0
2 -22.94 -45.40 0
3 -23.22 -45.80 1
*1000<threshold
移到了数组创建之外,这样这两个操作就可以以向量化的方式在整个数组上执行,而不是在每个单独的距离上执行。 - Ben.T