首页 > 解决方案 > 在 python 中使用 Foursquare API

问题描述

如何使用foursquare API提取城市每个社区的医院列表?并将其放入数据框中。

这就是我试图作为 DataFrame 实现的目标:

    Neighborhood  No. of hospitals
0  Neighborhood1                 5
1  Neighborhood2                 1
2  Neighborhood3                 3
3  Neighborhood4                 4
4  Neighborhood5                 5

我正在尝试以前教程中的代码来实现这一点,我预计会出现错误,但我不知道从哪里开始。

def getNearbyVenues(names, latitudes, longitudes, radius=500):

venues_list=[]
for name, lat, lng in zip(names, latitudes, longitudes):
    print(name)
        
    # create the API request URL
    url = 'https://api.foursquare.com/v2/venues/search?&client_id={}&client_secret={}&v={}&ll={}&query=supermarket,{}&radius={}&limit={}'.format(
        CLIENT_ID, 
        CLIENT_SECRET, 
        VERSION, 
        lat, 
        lng, 
        radius, 
        LIMIT)
        
    # make the GET request
    results = requests.get(url).json()["response"]['groups'][0]['items']
    
    # return only relevant information for each nearby venue
    venues_list.append([(
        name, 
        lat, 
        lng, 
        v['venue']['name'], 
        v['venue']['location']['lat'], 
        v['venue']['location']['lng'],  
        v['venue']['categories'][0]['name']) for v in results])

nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])
nearby_venues.columns = ['Neighborhood', 
              'Neighborhood Latitude', 
              'Neighborhood Longitude', 
              'Venue', 
              'Venue Latitude', 
              'Venue Longitude', 
              'Venue Category']

return(nearby_venues)

下一个单元格:

Toronto_venues = getNearbyVenues(names=Toronto_df['Neighborhood'],
                               latitudes=Toronto_df['Latitude'],
                               longitudes=Toronto_df['Longitude']
                              )

先感谢您!

标签: pythonpandasfoursquare

解决方案


谢谢您的答复,

Toronto_venues = getNearbyVenues(names=Toronto_df['Neighborhood'],
                               latitudes=Toronto_df['Latitude'],
                               longitudes=Toronto_df['Longitude']
                              )

但是这个单元格会返回这个错误,

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-16-03f6027f84a2> in <module>()
      1 Toronto_venues = getNearbyVenues(names=Toronto_df['Neighborhood'],
      2                                latitudes=Toronto_df['Latitude'],
----> 3                                longitudes=Toronto_df['Longitude']
      4                               )

<ipython-input-13-0c3ca691c166> in getNearbyVenues(names, latitudes, longitudes, radius)
     16 
     17         # make the GET request
---> 18         results = requests.get(url).json()["response"]['groups'][0]['items']
     19 
     20         # return only relevant information for each nearby venue

KeyError: 'groups' 

推荐阅读