0

I am working on Pandas and I am struggling to create a new column with information from an API over the rows of my dataframe.

The "location" column I want to iterate is a Series of dictionaries like this:

{'type': 'Point', 'coordinates': [-0.1394759, 51.5170385]}

My function:

def starbucks(df):
    API_key = os.getenv('API_KEY')
    lat = list(df["location"])[1]["coordinates"][1]
    lon = list(df["location"])[1]["coordinates"][0]
    base_url = "https://maps.googleapis.com/maps/api/place/textsearch/json?"
    endpoint = "query=starbucks&location={0},{1}&radius=1000&key={2}".format(lat, lon, API_key)
    res = requests.get(base_url+endpoint).json()

How I am implementing the apply function (currently with a 'location', 'occurred at index 61' error):

sample['testing'] = sample.apply(lambda x: starbucks(x["location"]), axis=1)

I've read some posts regarding the apply function and the documentation, but I am still missing something.

Help would be very much appreciated!

Thanks

irenels
  • 3
  • 2
  • Does this answer your question? [Pandas: How can I use the apply() function for a single column?](https://stackoverflow.com/questions/34962104/pandas-how-can-i-use-the-apply-function-for-a-single-column) – Eliot K Feb 10 '20 at 21:48
  • Why are you casting the columns to lists? `The "location" column I want to iterate is a Series of dictionaries like this:` Why not separate the data into multiple columns? – AMC Feb 11 '20 at 01:50

1 Answers1

0

Your function is expecting a data frame, but you are passing a value to it. I think your function should be:

def starbucks(val):
    API_key = os.getenv('API_KEY')
    lat = list(val)[1]["coordinates"][1]
    lon = list(val)[1]["coordinates"][0]
    base_url = "https://maps.googleapis.com/maps/api/place/textsearch/json?"
    endpoint = "query=starbucks&location={0},{1}&radius=1000&key={2}".format(lat, lon, API_key)
    res = requests.get(base_url+endpoint).json()
    return res

Here's another article that will give you more examples of how to use apply:
Pandas: How can I use the apply() function for a single column?

Eliot K
  • 614
  • 5
  • 16