当前位置: 代码迷 >> python >> Python Geopy接受手动字符串,但在通过CSV DF循环时不接受
  详细解决方案

Python Geopy接受手动字符串,但在通过CSV DF循环时不接受

热度:52   发布时间:2023-06-16 10:26:10.0

不知道为什么当我尝试获取位置信息时会发生这种情况。 我的示例csv具有以下内容

address,city,state,zip
767 5th Ave, New York, NY, 10153

和我的python文件看起来像这样,我在有问题的地方添加了注释

from geopy.geocoders import Nominatim
geolocator = Nominatim()
import pandas as pd

df = pd.read_csv('test.csv')

for index, row in df.iterrows():
    # doesnt work when looping
    location = geolocator.geocode(row['address'],row['city'],row['state'],row['zip'])

    # works manually
    #location = geolocator.geocode("767 5th Ave, New York, NY, 10153")
    print(location.raw)

这些不一样吗?

我这样解决了

for index, row in df.iterrows():
    street = str(row['address'])
    city = str(row['city'])
    state = str(row['state'])
    zipcode = str(row['zip'])
    location = geolocator.geocode("%s %s %s %s" % (street,city,state,zipcode))
    print(location.raw)

让我知道这是否是最有效的方法