简体   繁体   English

对于通过 pandas 数据帧的纬度和经度循环

[英]For loops through pandas dataframes for latitude and longitude

So I have a dataframe with two columns cities and counties that has some cities from Maryland USA.所以我有一个 dataframe 有两列城市和县,其中有一些来自美国马里兰州的城市。 I am trying to loop through to get the latitude and longitude coordinates for each city using the following code:我正在尝试使用以下代码循环获取每个城市的纬度和经度坐标:

from geopy.geocoders import Nominatim
latitude=[]
longitude=[]
for city in df["City"]:

    address = city + ', MD'

    geolocator = Nominatim(user_agent="tor_explorer")
    location = geolocator.geocode(address)
    latitude = location.latitude
    longitude = location.longitude
df['latitude']=latitude
df['longitude']=longitude

But when I print latitude or longitude there's only one value in the list so when I put it into the dataframe it just repeats the same latitude and longitude for every city.但是当我打印纬度或经度时,列表中只有一个值,所以当我将它放入 dataframe 时,它只会为每个城市重复相同的纬度和经度。

You are assigning the last value the for loop takes, so try to append each value of the for loop:您正在分配 for 循环采用的最后一个值,因此请尝试 append for 循环的每个值:

latitude=[]
longitude=[]
for city in df["City"]:

    address = city + ', MD'

    geolocator = Nominatim(user_agent="tor_explorer")
    location = geolocator.geocode(address)
    latitude.append(location.latitude)
    longitude.append(location.longitude)
df['latitude']=latitude
df['longitude']=longitude

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM