對于一個專案,我有一個帶有 60 個坐標和半徑(對于一個城區的每個質心)的 csv 檔案,我想獲取我的 Google 地圖結果。目的是遍歷坐標和半徑,并為每個列出的坐標接收一種特定型別(例如咖啡館)的所有現有地點。到目前為止,我能夠通過手動添加坐標來檢索結果,并且我正在努力將熊貓“應用”應用于我的“givePlaces”功能。
我使用 Pandas 匯入 csv 檔案并撰寫了一個回傳最大值的函式。可能的結果(<60,Google 不允許更多)。我定義了變數“位置”、“半徑”和“型別”。代碼如下所示,幾乎可以正常作業。也許你們中的一位可以提供幫助:
import googlemaps
import pprint
import time
import csv
import pandas as pd
from GoogleMapsAPIKey import get_my_key
#import the coordinates and radius csv-file
df = pd.read_csv('filepath',sep=';',header=0)
df
簡化后,csv 表如下所示:
| 緯度 | 經度 | 半徑 |
|---|---|---|
| 48.179037 | 11.522759 | 500 |
| 48.156327 | 11.414132 | 1200 |
#define my API Key
API_KEY = get_my_key()
gmaps = googlemaps.Client(key = API_KEY)
#Define a function that returns the Places API results:
def givePlaces(location, radius, type):
# define list of places of interest
places = []
# request first page
places_result = gmaps.places_nearby(location=location, radius=radius, type=type)
# add results to places
places = places places_result['results']
# while 'next_page_token' exists, request the next page and repeat
while('next_page_token' in places_result):
# wait 3 seconds before next request
time.sleep(3)
# overwrite places_result with results of second and/or third page
places_result = gmaps.places_nearby(page_token = places_result['next_page_token'])
# add these results to places
places = places places_result['results']
print("found " str(len(places)) " places")
return places
#Previously I used this manually:
location = 48.179037,11.522759
radius = 500
type = 'cafe'
my_places = givePlaces(location, radius, type)
#the apply function would look like this, but so far does not work:
df['places'] = df.apply(lambda row: givePlaces((row['L?nge'], row['Breite'], row['Radius'], 'cafe'), axis=1)
pprint.pprint(my_places)
任何人都可以幫助我使用熊貓應用功能嗎?我仍然是編碼的初學者,谷歌在我的具體問題上沒有太大幫助。非常感謝您!
uj5u.com熱心網友回復:
3件事:
- 不要命名變數
type,因為它也是一個內置的python函式 df.apply(lambda row: givePlaces((row['L?nge'], row['Breite'], row['Radius'], 'cafe'), axis=1)格式不正確,缺少括號,您需要將location傳遞為字串、字典、串列或元組。- 位置需要指定為緯度(Breite),經度(L?nge)
使用一個元組可以:
df.apply(lambda row: givePlaces((row['Breite'], row['L?nge']), row['Radius'], 'cafe'), axis=1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/359273.html
標籤:Python 熊猫 文件 google-places-api 熊猫应用
上一篇:在nodejs中決議CSV并獲取可在“結束”閉包之外訪問的內容陣列?
下一篇:如何基于跨差異列的值創建特征列
