Apply postcode API call to each row in dataframe

Viewed 153

In the below code block, I have a dataframe, geo, which I want to iterate over to get the easting, northing, longitude and latitude for each UK postcode in geo. I've written a function to call the API and another to return the four variables.

I've tested the get_data call with a postcode to prove it works (this is a public API anyone can use):

import requests 
import pandas as pd

geo = spark.table('property_address').toPandas()


def call_api(url: str) -> dict:
  postcode_response =requests.get(url)
  return postcode_response.json()

def get_data(postcode):

  url = f"http://api.getthedata.com/postcode/{postcode}"
  
  req = r.get(url)
  

  results = req.json()['data']
  easting = results['easting']
  northing = results['northing']
  latitude = results['latitude']
  longitude = results ['longitude']
  
  return easting ,northing,latitude, longitude

get_data('SW1A 1AA')

which returns:

Out[108]: (529090, 179645, '51.501009', '-0.141588')

Want I want to do is run that for each row in geo and return it as a dataset. My research has led me to apply, and I've based my attempt on this guide.

I'm trying to pass a column called property_postcode in geo and iterate each row to return the values, here's my attempt:

def get_columns(row):
  column_name = 'property_postcode'
  api_param = row[column_name]
  easting,northing,latitude,longitude = get_data(api_param)
  row['east'] = easting
  row['north'] = northing
  row['lat'] = latitude
  row['long'] = longitude
  return row

geo= geo.apply(get_columns, axis=1)

display(geo)

The error I get is

`JSONDecodeError: Expecting value: line 1 column 1 (char 0)`

Doesn't tell me a huge amount. Looking for assistance\pointers.

1 Answers

Instead of trying to set the values for the east, north, lat and long columns in the function return them from the function.

from numpy import result_type
import requests
import pandas as pd

# geo = spark.table('property_address').toPandas()


def call_api(url: str) -> dict:
    postcode_response = requests.get(url)
    return postcode_response.json()


def get_data(postcode):
    url = f"http://api.getthedata.com/postcode/{postcode}"
    req = requests.get(url)

    if req.json()["status"] == "match":
        results = req.json()["data"]
        easting = results.get("easting")
        northing = results.get("northing")
        latitude = results.get("latitude")
        longitude = results.get("longitude")
    else:
        easting = None
        northing = None
        latitude = None
        longitude = None

    return easting, northing, latitude, longitude


def get_columns(code):
    api_param = code
    return get_data(api_param)


df = pd.DataFrame(
    {
        "property_postcode": [
            "BE21 6NZ",
            "SW1A 1AA",
            "W1A 1AA",
            "DE21",
            "B31",
            "ST16 2NY",
            "S65 1EN",
        ]
    }
)

df[["east", "north", "lat", "long"]] = df.apply(
    lambda row: get_columns(row["property_postcode"]), axis=1, result_type="expand"
)

print(df)

property_postcode east north lat long
BE21 6NZ NaN NaN None None
SW1A 1AA 529090 179645 51.501009 -0.141588
W1A 1AA 528887 181593 51.518561 -0.143799
DE21 NaN NaN None None
B31 NaN NaN None None
ST16 2NY 391913 323540 52.809346 -2.121413
S65 1EN 444830 394082 53.44163 -1.326573
Related