我想从我的熊猫数据框中获取纬度和经度点的国家名称。目前我使用geolocator.reverse(纬度,经度)来获取地理位置的完整地址。但是,没有选项可以从完整地址中检索国家/地区名称,因为它返回一个列表。
使用方法:
def get_country(row):
pos = str(row['StartLat']) + ', ' + str(row['StartLong'])
locations = geolocator.reverse(pos)
return locations
通过传递dataframe来调用get_country:
df4['country'] = df4.apply(lambda row: get_country(row), axis = 1)
当前输出:
StartLat StartLong Address
52.509669 13.376294 Potsdamer Platz, Mitte, Berlin, Deutschland, Europe
只是想知道在我们传递地理点时是否有一些Python库来检索国家。
任何帮助,将不胜感激。
在你的get_country
函数中,你的返回值location
将有一个属性raw
,这是一个如下所示的字典:
{
'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']
给'Deutschland'
如果我正确地阅读了您的问题,可能的解决方案可能是:
def get_country(row):
pos = str(row['StartLat']) + ', ' + str(row['StartLong'])
locations = geolocator.reverse(pos)
return location.raw['address']['country']
编辑:location.raw对象的格式将根据您使用的geolocator服务而有所不同。我的示例使用geopy.geocoders.Nominatim,来自geopy's documentation site上的示例,因此您的结果可能会有所不同。
我不确定你使用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')
这将返回如下所示的词典列表:
[
{
"city": "Owosso",
"geohash": "dpshsfsytw8k",
"country": "US",
"county": "Shiawassee",
"state": "Michigan",
"state_short": "MI",
"postal_code": "48867",
"latitude": 42.9934,
"longitude": -84.1595,
"timezone": "America/Detroit"
}
]
我的代码,希望有助于:
from geopy.geocoders import Nominatim
nm = Nominatim()
place, (lat, lng) = nm.geocode("3995 23rd st, San Francisco,CA 94114")
print('Country' + ": " + place.split()[-1])