【发布时间】:2021-03-02 15:28:50
【问题描述】:
我正在自学geopy。看起来简单明了,但我的代码不起作用。它应该:
- 将地址字段列表从 CSV 读入
pandasdf - 将地址字段连接成一个格式为
geopy的列 - 从新列中列出一个列表
- 通过for循环将列表中的每个项目输入
geopy并返回坐标添加 坐标到原始 df 并将其导出为 CSV
#setup
from geopy.geocoders import Nominatim
import pandas as pd
#create the df
df = pd.DataFrame(pd.read_csv('properties to geocode.csv'))
df['Location'] = df['Street Address'].astype(str)+","+df['City'].astype(str)+","+df['State'].astype(str)
#create the geolocator object
geolocator = Nominatim(timeout=1, user_agent = "My_Agent")
#create the locations list
locations = df['Location']
#empty lists for later columns
lats = []
longs = []
#process the location list
for item in locations:
location = geolocator.geocode('item')
lat = location.latitude
long = location.longitude
lats.append(lat)
longs.append(long)
#add the lists to the df
df.insert(5,'Latitude',lats)
df.insert(6,'Longitude',longs)
#export
df.to_csv('geocoded-properties2.csv',index=False)
有些东西不起作用,因为它为每一行返回相同的纬度和经度值,而不是每行的唯一坐标。
我在其他地方找到了使用 .apply 的工作代码,但我有兴趣了解我做错了什么。有什么想法吗?
【问题讨论】:
-
location = geolocator.geocode('item')您传递的是字符串文字,而不是变量 item 的值 -
感谢您的回复。当我删除项目周围的“”时,出现以下错误:AttributeError:“NoneType”对象没有属性“纬度”
-
我提供了更广泛的答案。如果您提供的地址未找到
geolocator.geocode(),则返回None。这是我在返回之前编写的函数中明确测试过的
标签: python-3.x pandas for-loop geopy