将Foursquare API与python结合使用



如何使用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']
)

提前谢谢!

感谢您的回复,

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' 

您需要进行值计数,然后分离出任何列并重命名它。

df = Toronto_venues.groupby('Neighborhood').count()  # Get the counts
df = pd.DataFrame(df['Venue']) # Convert the counts to a dataframe
df.rename(columns={'Venue': 'No. of Hospitals'}, inplace=True)

此时,您将有一个数据帧,但第一列是您的医院名称,即索引。如果你想把它拉到一列中,那么也可以使用以下代码:

df.reset_index(level=0, inplace=True)

最新更新