#import packages
from arcgis import GIS
from arcgis.geometry import Point
import pandas as pd
#set input data filenames
fname_need = '../Data/raw/Basic_Data/1_Conservation_Need.shp'
fname_opportunity = '../Data/raw/Basic_Data/5_Combined_Opportunity.shp'
fname_hex = '../Data/raw/Hexagon_files/100km2_D1_LamAzimNeed.shp'
#set output data filenames
fname_hex_new = '../scratch/HexData.shp'
#read data into spatial dataframes
sdf_need = pd.DataFrame.spatial.from_featureclass(fname_need)
sdf_opportunity = pd.DataFrame.spatial.from_featureclass(fname_opportunity)
sdf_hex = pd.DataFrame.spatial.from_featureclass(fname_hex)
#Create a function that returns the centroid from a provided shape
def get_centroid(theShape):
x,y = theShape.centroid
sr = theShape.spatialReference['wkid']
return Point(F'{{"x": {x}, "y" :{y}, "spatialReference" : {{"wkid" : {sr}}}}}')
#Extract the centroids of all the hexagon features
the_centroids = sdf_hex['SHAPE'].apply(get_centroid)
#Iterate through all features in the NEEDS feature class
for i,row in sdf_need.iterrows():
#Status
print(i,end=' ')
#Get the shape
the_poly = row['SHAPE']
#Add new columns in the hex dataframe with 1's and 0's
col_name=F'need{i+1}'
sdf_hex[col_name]=the_centroids.apply(lambda x: 1 if x.within(the_poly) else 0)
#Iterate through all features in the OPPOR feature class
for i,row in sdf_opportunity.iterrows():
#Status
print(i,end=' ')
#Get the shape
the_poly = row['SHAPE']
#Add new columns in the hex dataframe with 1's and 0's
col_name=F'opp{i+1}'
sdf_hex[col_name]=the_centroids.apply(lambda x: 1 if x.within(the_poly) else 0)
#Get need and opportunity column names
need_cols = [c for c in sdf_hex.columns.tolist() if c[:4]=='need']
opp_cols = [c for c in sdf_hex.columns.tolist() if c[:3]=='opp']
#Tally sum of all added columns
sdf_hex['TOT_NEED'] = sdf_hex.loc[:,need_cols].sum(axis=1)
sdf_hex['TOT_OPP'] = sdf_hex.loc[:,opp_cols].sum(axis=1)
#Save to new file
outFC = sdf_hex.spatial.to_featureclass(fname_hex_new)