mabiel
mabiel

Reputation: 105

Mapping gps coordinates with census tract Python

I did not yet find an answer to solve my confusion of a small project I am working on.

My goal is to match a census block ID / block_fips to lat/lon pairs in my dataframe.

I have not worked with an API for complementing data in Python previously.

Here is a snippet of a dataset of lat and lon coordinates:

import pandas as pd
df = pd.DataFrame({'lat': [40.760659, 40.768254, 40.761573], 'lon': [-73.980420, -73.988639, -73.972628]})
print(df)

I came across the Census conversion API https://www.fcc.gov/census-block-conversions-api. If using the Area API, how can I (1) obtain and then (2) match the "block_fips" to the first lat/lon pair, in this case "360610131001003" using Python in a Jupyter notebook in the Anaconda environment.

The output I wish is then:

dfcensus = pd.DataFrame({'lat': [40.760659, 40.768254, 40.761573], 'lon': [-73.980420, -73.988639, -73.972628], 'block': [360610131001003, 360610139003000, 360610112021004]})
print(dfcensus)

Many thanks for any input!

Upvotes: 0

Views: 1124

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31146

  • a row by row call to the API is simplest approach
  • API is simple to use, use requests building URL parameters documented in API
  • just assign this back to new column in dataframe
  • this has been run in a jupyter lab environment
import requests

url = "https://geo.fcc.gov/api/census/block/find"

df = pd.DataFrame({"lat": [40.760659, 40.768254, 40.761573],
                   "lon": [-73.980420, -73.988639, -73.972628],})
df.assign(
    block=df.apply(
        lambda r: requests.get(
            url, params={"latitude": r["lat"], "longitude": r["lon"], "format": "json"}
        ).json()["Block"]["FIPS"],
        axis=1,
    )
)
lat lon block
0 40.7607 -73.9804 360610131001003
1 40.7683 -73.9886 360610139003000
2 40.7616 -73.9726 360610112021004

Upvotes: 1

Related Questions