|
POST
|
Hi Dan The following works great, just can't figure out how to use the following within an update cursor: The following is how far I've gotten: # environmental features within each settlement
def environmental_features(enviro_input):
enviro_intersect = []
for fcs in enviro_input:
orig_name = arcpy.Describe(fcs).name
input_features = ["Settlements_Amended", orig_name]
intersect_name = "{0}\\{1}_int".format("in_memory", orig_name)
arcpy.Intersect_analysis(input_features, intersect_name)
enviro_intersect.append(intersect_name)
merge_name = "{0}\\{1}_merge".format("in_memory", "Environmental")
arcpy.Merge_management(enviro_intersect, merge_name)
diss_name = "{0}\\{1}_diss".format(input_fgdb, "Environmental")
arcpy.Union_analysis(merge_name, diss_name, "ALL")
field_name = "ENVIRO_TYPE"
arcpy.AddField_management(diss_name, "ENVIRO_TYPE",
"TEXT",
field_length=100)
field_names = [f.name for f in arcpy.ListFields(diss_name, "TYPE*", "TEXT")]
cur_fields = list(field_names)
cur_fields.append(field_name)
with arcpy.da.UpdateCursor(diss_name, cur_fields)as ucur: # @UndefinedVariable
for row in ucur:
print row[0], row[1]
... View more
05-08-2016
01:16 PM
|
0
|
7
|
1818
|
|
POST
|
I'm creating a single feature class that will represent environmental areas within my study area. The environmental feature class is made up multiple feature classes that was merged, then union-ed . Each of the feature classes that were merged can contain a field "TYPE_RIV", "TYPE_WET", "TYPE_CBA", "TYPE_PROTECT". What I'm trying to achieve is a better way of populating a new field "TYPE" that will concatenate the TYPE field (i.e. "TYPE_RIV", "TYPE_WET" etc.) values automatically based on the input environmental feature classes as this can differ from study area to study area. In other words in some cases there will be "TYPE_RIV", "TYPE_WET" and other cases there will be "TYPE_RIV", "TYPE_WET", "TYPE_CBA" lastly "TYPE_RIV", "TYPE_WET", "TYPE_CBA", "TYPE_PROTECT" Once I've merged and union-ed the input feature classes, I'd like to identify the "TYPE_*" fields and concatenate the field fields into the new "TYPE" fields as per below: End Result Required: Current Code Block to Populate "TYPE" field I can easily get the "TYPE_*" fields using s a list fields search, but how can an automatically populate the "TYPE" field concatenating the fields correctly based on the fields within the list as the if statements are hard coded and not sure how to get around the following.
... View more
05-08-2016
08:12 AM
|
0
|
14
|
5207
|
|
POST
|
Hi Cynthia I eventually landed up re-writing the Centroidal Longest Flowpath Tool within Python. I've added the code below if you'd like to use it. Please note that you will need Python Pathlib Package or other wise replace it with os.path.join. Also note that the following feature class needs to be within the input file geodatabase: LongestFlowPath_2D (i.e. its the longest flow path feature class for each subwatershed or watershed) '''
Created on Feb 23, 2016
Determine CentroidalongestFlowPath
@author: PeterW
'''
# import site-packages and modules
from pathlib import Path
import arcpy
# set input and output arguments
fgdb = Path(r"E:\Projects\2016\G112491\ArcHydro\ArcHydro\Northern\Model01\Model01.gdb")
# set environment variables
arcpy.env.overwriteOutput = True
# add centroidalfl field to longestflowpath_2d
def centroidal_flow_line_field(fgdb):
longestflowpath_2d = "{0}\\{1}".format(Path(fgdb, "Layers"),
"LongestFlowPath_2D")
fieldname = "CentroidalFL"
fields = arcpy.ListFields(longestflowpath_2d)
for field in fields:
if field.name.lower() == fieldname.lower():
arcpy.DeleteField_management(longestflowpath_2d, fieldname)
arcpy.AddField_management(longestflowpath_2d, fieldname, "DOUBLE")
else:
arcpy.AddField_management(longestflowpath_2d, fieldname, "DOUBLE")
return longestflowpath_2d
longestflowpath_2d = centroidal_flow_line_field(fgdb)
# flip longestflowpath_2d downstream to upstream
def flip_longestflowpath(longestflowpath_2d):
arcpy.FlipLine_edit(longestflowpath_2d)
flip_longestflowpath(longestflowpath_2d)
# determine centroidal longest flowpath length and point geometry
def centroidal_flow_line_length(fgdb, longestflowpath_2d):
centroid = "{0}\\{1}".format(Path(fgdb, "Layers"), "Centroid")
centroidalfl_geometry = []
with arcpy.da.SearchCursor(centroid, ["SHAPE@", "DrainID"]) as scur: # @UndefinedVariable
for row1 in scur:
with arcpy.da.UpdateCursor(longestflowpath_2d, ["SHAPE@", "DrainID", "CentroidalFL"]) as upcur: # @UndefinedVariable
for row2 in upcur:
if row1[1] == row2[1]:
tpl = row2[0].queryPointAndDistance(row1[0], False)
row2[2] = tpl[1]
upcur.updateRow(row2)
centroidalfl_geometry.append(tpl[0])
return centroidalfl_geometry
centroidalfl_geometry = centroidal_flow_line_length(fgdb, longestflowpath_2d)
# flip longestflowpath_2d upstream to downstream
flip_longestflowpath(longestflowpath_2d)
# generate centroidal longest flowpath polylines from longestflowpath_2d
def centroidal_flow_line_polyline(fgdb, longestflowpath_2d,
centroidalfl_geometry):
centroidalfl_polyline = "{0}\\{1}".format(Path(fgdb, "Layers"),
"CentroidalFL")
arcpy.SplitLineAtPoint_management(longestflowpath_2d,
centroidalfl_geometry,
centroidalfl_polyline)
centroidalfl_length = []
with arcpy.da.SearchCursor(longestflowpath_2d, ["CentroidalFL"]) as scur: # @UndefinedVariable
for row in scur:
centroidalfl_length.append("{0:.6f}".format(row[0]))
with arcpy.da.UpdateCursor(centroidalfl_polyline, ["SHAPE@LENGTH"]) as upcur: # @UndefinedVariable
for row in upcur:
shape_length = "{0:.6f}".format(row[0])
if shape_length not in centroidalfl_length:
upcur.deleteRow()
centroidal_flow_line_polyline(fgdb, longestflowpath_2d, centroidalfl_geometry) Hope the following helps
... View more
05-07-2016
03:04 AM
|
1
|
0
|
1970
|
|
POST
|
Hi Dan Thanks Dan, will have a look at the following.
... View more
05-06-2016
08:18 AM
|
0
|
0
|
2084
|
|
POST
|
I've found a temporary solution to the following, using Summary Statistics. I'd really appreciate any advice in how to alter my NumPy Function to get the results out within the correct format. The following will allow me to get my results out today. Thanks for the advice so far.
... View more
05-06-2016
05:48 AM
|
0
|
6
|
2084
|
|
POST
|
Hi Wes The following is an output from Summary Statistics so you can't use Dissolve, thanks for the suggestion though.
... View more
05-06-2016
05:34 AM
|
0
|
0
|
2084
|
|
POST
|
Hi Dan Column C would be the same. The reason that the second image is different was just to show that there could be values from Time5 - Time60 depending of the statistics results. The second record within the second image would have been four records within the first image. I've replaced the second image to show only one record and filled the empty columns to depict that the Time range of possible results depending on the statistics results.
... View more
05-06-2016
04:15 AM
|
0
|
0
|
2084
|
|
POST
|
!I recently posted the following discussion Convert Summary Table Structure (Python) which I thought I'd resolved with the help from Dan Patterson. Please refer to my previous post for the explanation and the reasoning behind the following. Where I'm currently at is that I have been able to pivot the column Time and populate it with the values from the statistics count results. The last hurdle that I'm trying to achieve is to merge the results so that there isn't a new record for each time interval as shown below: Incorrect Pivot Results: Correct Pivot Results: '''
Created on April 6, 2016
Summarise Number of Buildings
per Time Interval
(5, 10, 15, 25, 30, 60)
@author: PeterW
'''
# import site-packages and modules
from pathlib import Path
import numpy.lib.recfunctions as rfn
import pandas as pd # Pandas version 0.13.0
import arcpy
# set arguments
saa_stats_table = r"E:\Projects\2016\G112224\Models\Schools\Schools_Combined_160505.gdb\Botrivier_Prim_SAA_Stats"
# environment settings
arcpy.env.overwriteOutput = True
fgdb = Path(saa_stats_table).parents[0]
def pivot_table(saa_stats_table, fgdb):
fields = [f.name for f in arcpy.ListFields(saa_stats_table)]
table_recarray = arcpy.da.TableToNumPyArray(saa_stats_table, fields) # @UndefinedVariable
print table_recarray
df = pd.DataFrame(table_recarray[fields])
pivot = df.pivot(index="OBJECTID",
columns="TIME",
values="FREQUENCY").fillna(0, downcast="infer")
pivot_fields = pivot.columns.values
# rename pivot fields with prefix "TIME"
pivot.columns = [("{0}{1}".format("TIME", field)) for field in pivot_fields]
# convert pandas dataframe to record array
pivot_recarray = pivot.to_records(index=False)
pivot_type = pivot_recarray.dtype.descr
pivot_type_new = [(x[0], x[1].replace(x[1], "<i2")) for x in pivot_type]
# change pivot record array data type to short integer
pivot_recarray = pivot_recarray.astype(pivot_type_new)
fields2 = ["TOWN", "SETTLEMENTNAME", "NAME"]
table_type_new = [(str(x), "<U25") for x in fields2]
# change table array data type to unicode 50 characters
table_recarray = table_recarray[fields2].astype(table_type_new)
recarray_list = [table_recarray, pivot_recarray]
# merge table and pivot record array
summary_array = rfn.merge_arrays(recarray_list, flatten=True, usemask=False)
summary_table = str(Path(fgdb, "SAA_Stats_Test"))
# convert merged record array to file geodatabase table
if arcpy.Exists(summary_table):
arcpy.Delete_management(summary_table)
arcpy.da.NumPyArrayToTable(summary_array, summary_table) # @UndefinedVariable
else:
arcpy.da.NumPyArrayToTable(summary_array, summary_table) # @UndefinedVariable
pivot_table(saa_stats_table, fgdb)
# Python Code: Any advice in how I can achieve the following. I suspect it would need to be done either before or after I have merged the two arrays (line 50). Any other alternative that won't require me having to change all my code would really be appreciated as time is a factor at the moment. I urgently need to get my results out. NB. Please note I dont have an Advance Licence so Pivot_Table is not an option. Thanks in advance.
... View more
05-06-2016
02:41 AM
|
0
|
11
|
7073
|
|
POST
|
Hi Dan Thanks for getting back to me on the following. By the way, I'm currently working through the NumPy Einsum Distance documentation that you provided me with as well as through the Numpy Reference Documentation to better understand how the following works. With regards to the moving of the points within the polygons. The following is only part of the rest of the algorithm that I'm currently busy developing. It's important that the points are at least 3m apart from each other but still within the polygon as they are going to refer back to the polygon once I have completed developing the following algorithm. The Building Footprints should not overlap each other, if they do its an topology error which I fix before running the following. I'll provide you an updated polygon and point dataset tonight, after I've ensured its clean of any topology errors. Thanks Dan for all the help and guidance.
... View more
04-25-2016
03:51 AM
|
1
|
0
|
1740
|
|
POST
|
Hi Chad The following will deal with the blanks within your date fields: def fnElapsed(STRDTTM, ENDDTTM):
from datetime import datetime
try:
dateStart = datetime.strptime(STRDTTM, "%d/%m/%Y %I:%M:%S %p")
dateEnd = datetime.strptime(ENDDTTM, "%d/%m/%Y %I:%M:%S %p")
timeDiff = dateEnd - dateStart
elapMin = timeDiff.total_seconds()/60
return elapMin
except Exception as inst:
print type(inst) fnElapsed(!STRDTTM!, !ENDDTTM!)
... View more
04-21-2016
02:03 PM
|
1
|
0
|
2291
|
|
POST
|
I thought I'd share the following with the community: '''
Created on Apr 18, 2016
Centroid
of Polygon
@author: PeterW
'''
import arcpy
from arcpy.arcobjects.geometries import PointGeometry
input_fc = r"E:\Proposals\2016\what3words\Calcs.gdb\ftr_dwellings_zola_tm19"
output_fc = r"E:\Proposals\2016\what3words\Calcs.gdb\Centroids_Test15"
def coord_sys(input_fc):
projection = arcpy.Describe(input_fc).spatialReference
return projection
projection = coord_sys(input_fc)
def centroid(input_fc, output_fc):
with arcpy.da.SearchCursor(input_fc, "SHAPE@XY") as scur: # @UndefinedVariable
centroid_coords = []
for feature in scur:
centroid_coords.append(feature[0])
point = arcpy.Point()
pointGeometryList = []
for pt in centroid_coords:
point.X = pt[0]
point.Y = pt[1]
pointGeometry = arcpy.PointGeometry(point, projection)
pointGeometryList.append(pointGeometry)
arcpy.CopyFeatures_management(pointGeometryList, output_fc)
centroid(input_fc, output_fc) Centroid: Center of Gravity '''
Created on Apr 18, 2016
Inner Centroid
of Polygon
@author: PeterW
'''
import arcpy
input_fc = r"E:\Proposals\2016\what3words\Calcs.gdb\ftr_dwellings_zola_tm19"
output_fc = r"E:\Proposals\2016\what3words\Calcs.gdb\Centroids_Test7"
def coord_sys(input_fc):
projection = arcpy.Describe(input_fc).spatialReference
return projection
projection = coord_sys(input_fc)
def inner_centroid(input_fc, output_fc):
inner_centroid_geom = []
with arcpy.da.SearchCursor(input_fc, "SHAPE@") as scur: # @UndefinedVariable
for feature in scur:
inner_centroid_pnt = arcpy.PointGeometry(feature[0].labelPoint, projection)
inner_centroid_geom.append(inner_centroid_pnt)
arcpy.CopyFeatures_management(inner_centroid_geom, output_fc)
inner_centroid(input_fc, output_fc) Centroid: Inner Centroid
... View more
04-18-2016
02:57 PM
|
0
|
1
|
3088
|
|
POST
|
Hi Dan I've attached the zipped file geodatabase containing the point and polygon features. A few points that need to be taken into consideration: I really like to keep the points as central as possible When moving the points they need to be moved with half meter increments Once the points have been moved they will need to be rechecked to ensure they are not within 3m or less of the other points The points are representing the polygons that they are falling within. The points are then being used to obtain a unique id, based on a spheriod grid system of 3m grids (or less closer to the poles). Unfortunately I don't have access to the grid before requesting the unique id. So by ensuring that the points are at least 3m apart from each other, I'm ensured that the returned id is unique for each building footprint. Thanks Dan
... View more
04-17-2016
12:08 AM
|
0
|
2
|
1740
|
|
POST
|
HI Dan Thanks, will give me a chance to figure it out first before you post the answer . Thanks for being such a great teacher. I have learnt a great deal from you already. My Python skill set has grown tremendously over the last 3 months.
... View more
04-16-2016
01:48 PM
|
0
|
0
|
2744
|
|
POST
|
Thanks Dan, much appreciated. Will get back to you once I've done my homework
... View more
04-16-2016
01:33 PM
|
0
|
2
|
2744
|
|
POST
|
Please note that I only have a ArcGIS Standard Licence. I have posted the following "Python Near Analysis (No Advanced Licence)" . Dan Patterson has provided me with some homework, which I'll be going through. I have another question that builds onto of the following. Once I've determined the shortest distance between each point feature. I'd like to filter out the point features that are within 3m or less of each other. I'm then looking for proximity techniques of being able to move the point features away from each other until they are over 3m away from each other, but still within the blue polygons. Any suggestions and workflows using Python will be appreciated.
... View more
04-16-2016
01:32 PM
|
0
|
6
|
5434
|
| Title | Kudos | Posted |
|---|---|---|
| 3 | 01-16-2012 02:34 AM | |
| 1 | 05-07-2016 03:04 AM | |
| 1 | 04-10-2016 01:09 AM | |
| 1 | 03-13-2017 12:27 PM | |
| 1 | 02-17-2016 02:34 PM |
| Online Status |
Offline
|
| Date Last Visited |
03-04-2021
12:50 PM
|