States Have the Most Neighbors?Ritvik KharkarBlockedUnblockFollowFollowingApr 30Photo by Joey Csunyo on UnsplashThis is going to be a pretty quick and dirty post on using python to determine whether one U.
state (or any arbitrary geography) borders another U.
state (or any other arbitrary geography).
Our input will be a GeoJSON (just a JSON describing a complex shape) of U.
States, which you can get from my GitHub here.
And, our output will be a dictionary in python which maps each U.
state to a single number indicating how many neighboring states it has.
Our main tool for this post will be the python library shapely which helps us manipulate complex geographies in python.
The procedure will be pretty straightforward: for each U.
state, we can loop over every other U.
state and then check whether or not the two states touch.
If they do, we can update a running list of neighboring states for the current state in question.
First we will need to convert the GeoJSON into objects that shapely can understand.
The two main shapely objects that we’ll be using are:Polygon objects: basically a single bounded shapeMultiPolygon objects: basically a collection of Polygon objects (because some U.
states consist of multiple geographic pieces)Here’s the code to parse the GeoJSON:Now that we’ve got a nice dictionary of state geography objects (either Polygons or MultiPolygons) in statePolygons, we can iterate through the dictionary and check whether each state neighbors each other state.
And, the result is:Nice!.So Missouri and Tennessee tie for first with 8 neighbors each and then Kentucky and Colorado tie for second with 7 each.
Hope this post helped a bit as a gentle intro in using shapely for spatial applications.
Thanks for reading!.