从Python中的地理位置检索国家

2024-10-01 15:37:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从pandas数据框中的经纬度点获取国家名称。 目前我已经使用地理定位器.reverse(纬度、经度)获取地理位置的完整地址。但是没有从完整地址检索国家名称的选项,因为它返回一个列表。在

使用方法:

 def get_country(row):
     pos = str(row['StartLat']) + ', ' + str(row['StartLong'])
     locations = geolocator.reverse(pos)
     return locations

通过传递数据帧调用get_country:

^{pr2}$

电流输出:

StartLat                  StartLong           Address          
52.509669              13.376294          Potsdamer Platz, Mitte, Berlin, Deutschland, Europe

只是想知道当我们经过地理点时是否有一些Python库来检索这个国家。在

任何帮助都将不胜感激。在


Tags: 数据pos名称pandasget地址国家country
3条回答

get_country函数中,返回值location将有一个属性raw,它是一个如下所示的dict:

{
  'address': {
     'attraction': 'Potsdamer Platz',
     'city': 'Berlin',
     'city_district': 'Mitte',
     'country': 'Deutschland',
     'country_code': 'de',
     'postcode': '10117',
     'road': 'Potsdamer Platz',
     'state': 'Berlin'
   },
   'boundingbox': ['52.5093982', '52.5095982', '13.3764983', '13.3766983'],
   'display_name': 'Potsdamer Platz, Mitte, Berlin, 10117, Deutschland',
   ... and so one ...
}

所以location.raw['address']['country']给出{}

如果我没看错你的问题,一个可能的解决办法是:

^{pr2}$

编辑:格式位置.raw对象将因使用的地理定位器服务而异。我的示例使用geopy.geocoders.提名,因此您的结果可能不同。在

我不知道你在geopy上使用的是什么服务,但作为一个我可能倾向于使用的小插头,我认为这对你来说可能是一个更简单的解决方案。在

https://github.com/Ziptastic/ziptastic-python

from ziptastic import Ziptastic

# Set API key.
api = Ziptastic('<your api key>')
result = api.get_from_coordinates('42.9934', '-84.1595')

它将返回如下字典列表:

^{pr2}$

我的代码,希望能帮助:

from geopy.geocoders import Nominatim 
nm = Nominatim()

place, (lat, lng) = nm.geocode("3995 23rd st, San Francisco,CA 94114")
print('Country' + ": " + place.split()[-1])

相关问题 更多 >

    热门问题