本文介绍了如何从邮政编码中获取坐标并将其添加到使用循环的df中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框:
d = {'Postcode': ['M3A','M4A','M5A','M6A','M9A','M1B'], 'Borough': ['North York', 'Downtown Toronto', 'Etobicoke',
'Scarborough', 'East York', 'York'],
'Neighbourhood': ['Parkwoods', 'Victoria Village', 'Harbourfront', 'Regent Park',
'Lawrence Heights', 'Lawrence Manor']}
post_df = pd.DataFrame(data = d)
Wich会产生类似的内容:
Wich yields something like:
Postcode Borough Neighbourhood
0 M3A North York Parkwoods
1 M4A Downtown Toronto Victoria Village
2 M5A Etobicoke Harbourfront
3 M6A Scarborough Regent Park
4 M9A East York Lawrence Heights
5 M1B York Lawrence Manor
我想获取每个邮政编码的所有纬度和经度.我想出了这样的代码:
I want to get all the latitudes and longitudes for each postal code.I figured out this code to do so:
import geocoder
# initialize your variable to None
lat_lng_coords = None
# loop until you get the coordinates
while(lat_lng_coords is None):
g = geocoder.google('{}, Toronto, Ontario'.format(postal_code_from_df))
lat_lng_coords = g.latlng
latitude = lat_lng_coords[0]
longitude = lat_lng_coords[1]
现在我的问题是:使用前面的代码,我想获取每个邮政编码的每个纬度和经度,并将它们添加到此现有df中称为纬度"和经度"的2个新列中.我该如何使用单个循环来避免一一搜索每个邮政编码坐标?
now my question is: Using the previous code, i would like to get each latitude and longitude for each postal code and add them to 2 new columns in this existing df called 'Latitude' and 'Longitude'. How could i do that using a single loop to avoid searching each postal code coordinates one by one?
非常感谢您
推荐答案
您可以使用df.apply
.像这样:
post_df['Latitude'], post_df['Longitude'] = zip(*post_df['Postcode'].apply(get_geocoder))
可以按@Ankur所述定义get_geocoder
的地方
Where get_geocoder
can be defined as mentioned by @Ankur
这篇关于如何从邮政编码中获取坐标并将其添加到使用循环的df中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!