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

如何遍历Pandas DataFrame按花卉分组查找最小距离?

按花卉分组计算到指定地点的最小距离解决方案

核心思路

不用手动遍历每一行,利用Pandas的groupby按花卉名分组,结合geopy批量计算每个种植地到目标地点(如芝加哥)的距离,再对每组取最小值,高效处理3000+行数据。

步骤实现

1. 安装依赖

先确保安装geopy库:

pip install geopy

2. 完整代码示例

import pandas as pd
from geopy.geocoders import Nominatim
from geopy.distance import geodesic

# 初始化地理编码器,user_agent设为你的应用标识(比如个人邮箱)
geolocator = Nominatim(user_agent="flower_distance_calculator")

# 预先获取目标地点(芝加哥)的经纬度,避免重复请求
target_location = geolocator.geocode("Chicago")
target_coords = (target_location.latitude, target_location.longitude)

# 定义计算单地点到芝加哥的英里距离函数
def calculate_distance(place):
    try:
        location = geolocator.geocode(place)
        if location:
            place_coords = (location.latitude, location.longitude)
            return geodesic(target_coords, place_coords).miles
        return float('inf')  # 找不到地点时设为无穷大,不影响取最小值
    except:
        return float('inf')

# 替换成你的实际DataFrame数据
data = {
    "Name": ["Geranium", "Geranium", "Geranium", "Daffodil", "Daffodil", "Daffodil", "Daffodil", "Carnations", "Carnations"],
    "Place": ["Paris", "Amsterdam", "Copenhagen", "Washington", "Helsinki", "Tokyo", "Sydney", "Kiambu", "Athens"]
}
df = pd.DataFrame(data)

# 按花卉分组,计算每组的最小距离
min_distances = df.groupby("Name")["Place"].apply(lambda x: x.apply(calculate_distance).min()).reset_index(name="Min Distance (miles)")

# 格式化输出为要求的列表形式
for _, row in min_distances.iterrows():
    print(f"- {row['Name']} - {row['Min Distance (miles)']:.2f} miles")

3. 针对3000+行数据的优化建议

  • 缓存地理编码结果:如果DataFrame中有重复的Place,用字典缓存已编码的经纬度,避免重复调用Nominatim接口,大幅提升速度:
    coords_cache = {}
    def calculate_distance(place):
        if place in coords_cache:
            place_coords = coords_cache[place]
        else:
            try:
                location = geolocator.geocode(place)
                if location:
                    place_coords = (location.latitude, location.longitude)
                    coords_cache[place] = place_coords
                else:
                    return float('inf')
            except:
                return float('inf')
        return geodesic(target_coords, place_coords).miles
    
  • 批量地理编码:如果数据量极大,可考虑使用批量地理编码工具,减少接口请求次数,进一步提升效率。

输出示例

运行代码后会得到类似结果:

  • Geranium - 1732.40 miles
  • Daffodil - 563.78 miles
  • Carnations - 3943.21 miles

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:36:32