geocoder.osm() 是一個 API 函式,它應該接受兩個引數:緯度和經度,然后將國家/地區名稱及其所有資訊作為 json 檔案回傳。
我有一個包含 70 萬行坐標的大資料框,我撰寫了以下代碼來提取每個坐標的國家/地區名稱:
import geocoder
import itertools
count=itertools.count(start=0)
def geo_rev(x):
print('starting: ',next(count))
g = geocoder.osm([x.latitude, x.longitude], method='reverse').json
try:
if g:
return [g.get('country'),g.get('city')]
else:
return ['no country','no city']
except ValueError:
pass
data[['Country','City']]=data[['latitude','longitude']].apply(geo_rev,axis=1,result_type='expand')
如你所見,我們傳遞了兩個值的串列中的每一行:[x.latitude, x.longitude]。
問題是:這段代碼將永遠執行,這就是為什么我想為函式傳遞一個串列串列geocoder.osm()以使請求更快,我的想法是執行以下代碼:[list[latitude...],list[longitude...] ],怎么做?
型別錯誤:float() 引數必須是字串或數字,而不是“串列”
但是如果我的想法(關于傳遞串列串列)是錯誤的,如果有另一種方法可以更快地呼叫 API,請告訴我。
uj5u.com熱心網友回復:
我不確定是什么問題,但是如果您需要嘗試獲取串列的元素,請嘗試使用“for i in list_name”,它會一一獲取元素。如果您需要兩個串列的元素,請嘗試“for i in range(len(list_name)): function(list_name[0][i],list_name[1][i])”
uj5u.com熱心網友回復:
我找到了我的問題的答案,使用串列串列看起來很難做到,然后我嘗試使用Threading,Threading 以非常高的速度為 asyncio 等 API 執行probably even ten times or twenty times faster它不會等待每個請求接收其檔案,但它同時發送幾個請求,然后同時接收它們的檔案,以下代碼將正常作業:
import geocoder
import itertools
import concurrent.futures
lst=list(zip(data.latitude.tolist(), data.longitude.tolist()))
countries=[]
count=itertools.count(start=0)
def geo_rev(x):
print('starting: ',next(count))
g = geocoder.osm([x[0], x[1]], method='reverse').json
try:
if g:
return g.get('country')
else:
return 'no country'
except ValueError:
pass
with concurrent.futures.ThreadPoolExecutor() as executor:
results=executor.map(geo_rev, lst)
for result in results:
countries.append(result)
data['Country']=[x for x in countries]
感謝 Corey Schafer 的視頻,它解釋了一切。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/400268.html
