pythonpandasapiloopsfoursquare

Using a loop on a pandas dataframe to make Foursquare call


Stuck on a step in a project. For this part I have a dataframe (df_income_zip_good) which has information about top 100 towns in the US in terms of per capita income.

The dataframe looks like this:

df_income_zip_good.head()

I've run a loop on this dataframe with folium and have been able to map with no problem.

for i, series in df_income_zip_good.iterrows():
    lat = series ['lat']
    lng = series ['lng']
    town = series ['place']

    folium.Marker (location=[lat,lng], popup = town, icon = folium.Icon(color='blue')).add_to(map_usa)
map_usa

folium map plotting locations from df_income_zip_good

I am unsuccessfully trying to write another loop that would scrape information from foursquare for each combination of latitude, longitude in df_income_zip_good.

 # scraping the foursquare website for the information we want and obtaining the json file as results

for i, series in df_income_zip_good.iterrows():
    lat = series ['lat']
    lng = series ['lng']
    town = series ['place']
    LIMIT = 100
    radius = 1000
    url4Sqr = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(
        CLIENT_ID,
        CLIENT_SECRET,
        VERSION,
        lat,
        lng,
        radius,
        LIMIT)

#export results to json file
result4Sqr = requests.get(url4Sqr).json()["response"]['groups'][0]['items']


#print results from call
print (result4Sqr)

The requested json prints out, but it only does so for one row in df_income_zip_good. It doesn't appear to be looping throughout df_income_zip_good.

Not sure where to go, and any guidance would be appreciated.

Thanks!


Solution

  • If you look at your code

    or i, series in df_income_zip_good.iterrows():
        ...
    
    #export results to json file
    result4Sqr = requests.get(url4Sqr).json()["response"]['groups'][0]['items']
    
    
    #print results from call
    print (result4Sqr)
    

    The last lines aren't part of the loop (they are not indented like the others). So the loop is first executed, and then the other lines are executed on the values last set in the loop.