0

I'm trying to calculate the queen contiguity weights using pysal's queen_from_shapefile() helper method based on this page

Not being a GIS specialist I wanted to check my intuition on this Q&A site first before proceeding further in my project. I'm using Shapely, GeoPandas and PySAL. Code follows, then question:

import pandas as pd
import geopandas as gpd
from shapely.geometry import Point, Polygon
import requests
import json
import time
import sys
import pysal as ps

testdf = (pd.DataFrame({'postCode': ["NE18 0AD", "TF4 3AL", "PL3 4PJ", "DD8 4BZ", "ML8 4FJ", 
                                   "TW20 2DQ", "CA26 3AS", "M3 4DT", "PA72 6JH", "EC3N 1LA"], 
                     'hasAttribute': [0, 1, 0, 0, 1, 0, 1, 0, 0, 0]}))
//random postcodes from here: https://www.doogal.co.uk/PostcodeGenerator.php
postcodelist = list(testdf.postCode)
url = 'http://api.postcodes.io/postcodes'
headers = {'content-type': 'application/json'}
lats = []
longs = []
payload = {'postcodes' : postcodelist }
r = requests.post(url, data=json.dumps(payload),  headers=headers)

time.sleep(0.1)
if r.status_code is 200:
    returnData = r.json()
    sys.stdout.write('.')
else:
    print("Query failed, status: %d".format(r.status_code))

result = returnData['result']
# Lets comprehend the list to get the lat and log data
# We need an if statement to catch cases where the postcode cant be found
lats += [ result[idx]['result']['latitude'] if result[idx]['result'] is not None else np.nan for idx in range(len(result)) ]
longs += [ result[idx]['result']['longitude'] if result[idx]['result'] is not None else np.nan for idx in range(len(result)) ]
testdf['lat'], testdf['long'] = lats, longs

polygon_geom = Polygon(zip(list(testdf.long), list(testdf.lat)))
polygon_list = [polygon_geom for i in range(testdf.shape[0])]
crs = {'init': 'epsg:4326'}
polygondf = gpd.GeoDataFrame(testdf, crs=crs, geometry=polygon_list)   
polygondf.to_file("testpoly.shp")
qW = ps.queen_from_shapefile("testpoly.shp")

Is it correct to assume the same Polygon for all rows of the dataframe for calculating queen weights and, if not, what is the correct approach?

  • 1
    We dont know what you are trying to do since you do not describe the task, only paste alot of code – BERA Sep 15 at 15:14
  • I'm trying to calculate the queen contiguity weights using pysal's queen_from_shapefile() helper method based on this page – shanlodh Sep 15 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.