经纬度查询英国邮编时出现'NoneType不可下标'错误求助
问题解决:坐标转英国邮编的Nonetype错误优化方案
错误原因
你的代码里req.get("result")[0]直接取结果的第一个元素,但如果API请求失败(比如网络问题)、坐标无效或者没有匹配到邮编时,req.get("result")会返回None,这时对None做下标操作就会触发报错。
修复后的单条查询函数
先给带错误处理的单条查询版本,确保程序不会崩溃:
import requests import pandas as pd def get_postcode(lon, lat): try: r = requests.get(f"http://api.postcodes.io/postcodes?lon={lon}&lat={lat}") r.raise_for_status() # 检查请求是否成功(比如404、500错误) req = r.json() # 直接用response的json方法,比json.loads更简洁 result = req.get("result") if result and len(result) > 0: return result[0]["postcode"] else: return None # 没有匹配到邮编时返回空值 except Exception as e: print(f"处理坐标({lon}, {lat})时出错: {str(e)}") return None # 应用到DataFrame df['Postcode'] = df.apply(lambda row: get_postcode(row.Longitude, row.Lattitude), axis=1)
更高效的批量查询方案
postcodes.io支持批量查询坐标转邮编,比逐条apply效率高很多(尤其当DataFrame数据量大时),推荐使用:
def batch_get_postcodes(df): # 构造批量请求的格式 batch_data = [{"longitude": row.Longitude, "latitude": row.Lattitude} for _, row in df.iterrows()] try: r = requests.post("http://api.postcodes.io/postcodes", json={"geolocations": batch_data}) r.raise_for_status() results = r.json()["result"] # 提取每个坐标对应的邮编,批量返回结果的顺序和请求顺序一致 postcodes = [] for res in results: if res["result"]: postcodes.append(res["result"][0]["postcode"]) else: postcodes.append(None) return postcodes except Exception as e: print(f"批量查询出错: {str(e)}") return [None] * len(df) # 批量添加到DataFrame df['Postcode'] = batch_get_postcodes(df)
关键优化点
- 增加异常捕获:处理网络错误、API返回错误等情况,避免程序崩溃
- 用
r.json()替代json.loads(r.content):更简洁且符合requests库最佳实践 - 批量查询减少API请求次数:大幅提升大数据量下的处理效率
- 明确处理无匹配结果的情况:返回
None而非抛出错误,保证DataFrame能正常生成新列
内容的提问来源于stack exchange,提问作者Alastairstirling
相关产品推荐
相关产品推荐

