Python 3.x 使用apply()加速数据帧上的嵌套循环
我有一个在Python中使用Pandas的数据帧,它在每一行上包含纬度和经度坐标。我的目标是使用haversine添加另一个名为close_by的列,该列包含数据集中1英里以内的其他条目的计数 我见过其他类似问题的指南,如:但它们涉及使用df.apply更新每一行,以添加坐标之间的距离和每个定义点的一些静态值。我还没有找到或想出解决办法 本质上,这就是我试图优化的:Python 3.x 使用apply()加速数据帧上的嵌套循环,python-3.x,pandas,numpy,lambda,Python 3.x,Pandas,Numpy,Lambda,我有一个在Python中使用Pandas的数据帧,它在每一行上包含纬度和经度坐标。我的目标是使用haversine添加另一个名为close_by的列,该列包含数据集中1英里以内的其他条目的计数 我见过其他类似问题的指南,如:但它们涉及使用df.apply更新每一行,以添加坐标之间的距离和每个定义点的一些静态值。我还没有找到或想出解决办法 本质上,这就是我试图优化的: for index1, row1 in business_data.iterrows(): for index2, row
for index1, row1 in business_data.iterrows():
for index2, row2 in business_data.iterrows():
distance = mpu.haversine_distance((business_data.at[index1,'latitude'], business_data.at[index1,'longitude']), (business_data.at[index2,'latitude'], business_data.at[index2,'longitude']))
distance = distance * 0.621371
if distance <= 1:
business_data.at[index1,'close_by'] = row1["close_by"] + 1
我有大约50000行,在我的电脑上,每行大约需要5秒钟
谢谢你的建议 从外观上看,mpu.haversine_距离使用数学而不是numpy函数,因此它不可矢量化
使用,您可以轻松地将问题矢量化:
df = pd.DataFrame([
{'latitude': 49.001, 'longitude': 11.0},
{'latitude': 49.0, 'longitude': 11.0},
{'latitude': 49.001, 'longitude': 11.001},
{'latitude': -49.0, 'longitude': 11.0},
])
lon = df['longitude'].to_numpy()
lat = df['latitude'].to_numpy()
radius = 1.0
df['close_by'] = np.count_nonzero(haversine_np(lon, lat, lon[:, None], lat[:, None]) < radius, axis=0) - 1
df
# latitude longitude nearby
# 0 49.001 11.000 2
# 1 49.000 11.000 2
# 2 49.001 11.001 2
# 3 -49.000 11.000 0
你能发布一些示例数据吗?谢谢你的解决方案,它回答了我的问题。但是,有没有办法使它的内存效率提高一点?它似乎在一段时间后抛出内存错误之前锁定了我的计算机。你可以处理你的数据帧