You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为房屋DataFrame添加最近地铁站名称列(已实现距离计算)

解决房屋数据添加最近地铁站名称列的问题

你已经能算出每个房屋到最近地铁站的距离,但还没法关联对应的地铁站名称,只需要修改原来的compute_distance函数,让它同时返回最小距离和对应地铁站名称即可,具体操作如下:

修改计算函数

原函数仅记录了最小距离,现在要同时跟踪对应的地铁站名称:

from geopy.distance import geodesic
import pandas as pd

def compute_nearest_station(flat, stations):
    flat_lat, flat_lon = flat[['Latitude','Longitude']]
    min_distance = float('inf')  # 用inf替代固定值9999.0,适配更大距离场景
    nearest_station = ""
    
    # 遍历所有地铁站,同时获取名称、纬度、经度
    for _, station in stations.iterrows():
        station_lat = station['Latitude']
        station_lon = station['Longitude']
        station_name = station['Station']
        
        # 计算当前房屋到该地铁站的距离(单位:米)
        distance = geodesic((flat_lat, flat_lon), (station_lat, station_lon)).m
        
        # 更新最小距离和对应站名
        if distance < min_distance:
            min_distance = distance
            nearest_station = station_name
    
    # 返回最小距离和最近地铁站名称,用Series方便后续合并
    return pd.Series([min_distance, nearest_station], index=['Nearest_MRT_Distance(m)', 'Nearest_MRT_Station'])

应用函数并合并到房屋DataFrame

调用修改后的函数,将结果直接合并到原房屋数据中:

# 假设你的房屋DataFrame名为flat_df,地铁站DataFrame名为station_df
result = flat_df.apply(compute_nearest_station, axis=1, stations=station_df)

# 合并结果到原房屋DataFrame
flat_df = pd.concat([flat_df, result], axis=1)

处理完成后,房屋DataFrame会新增两列:Nearest_MRT_Distance(m)(最近距离,单位为米)和Nearest_MRT_Station(对应地铁站名称)。

内容的提问来源于stack exchange,提问作者N_ote

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:39:28