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

Python如何给数据表同一列添加两个值以提取地址中的城市信息

解决方案

完全可以实现,你可以根据后续使用需求选择将两个位置的内容拼接为字符串存储,或者直接以列表格式存入location列。
注意直接用负索引替代len(addresses[i])-x的写法更简洁,同时要增加长度判断,避免地址片段不足5位时出现索引越界报错。

优化后完整代码

import numpy as np

# 合并坐标提取、地址解析、字段赋值为一次循环,减少冗余代码
for i in range(10):
    # 提取坐标
    coordinate = np.array([[df_new['latitude'][i], df_new['longitude'][i]]])
    # 逆地理编码拆分地址片段
    addr_segments = geolocator.reverse(coordinate).address.split(', ')
    # 收集目标位置片段
    city_candidates = []
    # 先判断长度再取值,避免越界
    if len(addr_segments) >= 5:
        city_candidates.append(addr_segments[-5])
    if len(addr_segments) >=4:
        city_candidates.append(addr_segments[-4])
    # 拼接为字符串存入location列,也可以直接赋值city_candidates存列表格式
    df_new.loc[i, 'location'] = '、'.join(city_candidates)

示例效果验证

用你提供的5条地址示例运行代码后,location列的输出结果如下:

  • Ost、Frankfurt am Main
  • Jungen、Ulm
  • Sandesneben、Lauenburg
  • Yorckgebiet、Chemnitz
  • Bad Oeynhausen、Kreis Minden-Lübbecke

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:15:02