#!/usr/bin/env python # coding: utf-8 # ### Objective # * Create a database of hexagons with a column for each need polygon # # ### Workflow # * Import data into spatial dataframes # * Hexagons feature class # * Conservation need feature class # * Iterate through each feature in the Needs dataframe # * Extract the feature's shape # * Select all Hexagons that have their center in the shape # * In a new column in the hexagon's dataframe, set values to 1 for selected row # In[ ]: #import packages from arcgis import GIS from arcgis.geometry import Point import pandas as pd # In[ ]: #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' # In[ ]: #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) # In[ ]: #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}}}}}') # In[ ]: #Extract the centroids of all the hexagon features the_centroids = sdf_hex['SHAPE'].apply(get_centroid) # In[ ]: #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) # In[ ]: #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) # In[ ]: #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'] # In[ ]: #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) # In[ ]: #Save to new file outFC = sdf_hex.spatial.to_featureclass(fname_hex_new)