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

遍历经纬度DataFrame调用逆地理编码查邮编时遇TypeError求助

问题解决方法

第一个DataFrame遍历问题

错误原因:循环中传入的df["Latitude"]和df["Longitude"]是整列的Pandas Series数据,而geocoder.google的reverse方法需要单个纬度/经度数值对,无法处理整列数据,因此触发类型错误。

修正后的代码:

import pandas as pd
import geocoder

df = pd.read_csv("Bunnings Co-Ordinates.csv")

# 遍历每一行数据
for idx, row in df.iterrows():
    # 取当前行的单个纬度和经度组成坐标对
    g = geocoder.google([row["Latitude"], row["Longitude"]], method='reverse', key="API_KEY")
    if g.postal:  # 避免空值引发报错
        print(f"门店 {row['Store']} 邮编:{g.postal}")

更高效的apply写法:

import pandas as pd
import geocoder

df = pd.read_csv("Bunnings Co-Ordinates.csv")

def get_postal_code(row):
    g = geocoder.google([row["Latitude"], row["Longitude"]], method='reverse', key="API_KEY")
    return g.postal if g.postal else None

# 新增列存储邮编
df["PostalCode"] = df.apply(get_postal_code, axis=1)
print(df[["Store", "PostalCode"]])

第二个坐标列表遍历问题

错误原因:循环中传入的是整个latitudes和longitudes列表,geocoder.google收到的是嵌套列表结构,无法解析为单个坐标数值,因此触发类型错误。

修正后的代码:

import geocoder

latitudes = [-27.59041, -34.93522]
longitudes = [153.02848, 138.53637]

# 用zip将纬度和经度一一配对
for lat, lng in zip(latitudes, longitudes):
    g = geocoder.google([lat, lng], method='reverse', key="API_KEY")
    if g.postal:
        print(f"坐标({lat}, {lng}) 邮编:{g.postal}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:13:15