2016-11-15 36 views
0

我想從我的熊貓數據框中獲取緯度和經度點的國家名稱。 目前我使用geolocator.reverse(緯度,經度)來獲取地理位置的完整地址。但沒有選項可以從完整地址中檢索國家名稱,因爲它會返回一個列表。從Python中的地理位置檢索國家

方法使用:

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

呼叫通過將數據幀到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庫檢索我們通過地理點的國家。

任何幫助,將不勝感激。

+0

你不能分割地址並從列表元素 - 即。 ''波茨坦廣場,米特,柏林,德國,歐洲「.split(」,「)[ - 2]' – furas

+0

你使用什麼模塊? – furas

+0

@furas:我當前使用geolocator.reverse() – user3447653

回答

2

在你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上的示例,因此您的結果可能會有所不同。

0

我不確定你使用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" 
    } 
] 
相關問題