|
POST
|
Hi Peter, First of all you should really use syntax highlighting, since it makes it easier to see where the error in code are: Posting Code blocks in the new GeoNet So you first part of the code, after deleting some redundant code (and spaces) and correcting some indentation would be: import arcpy
# Set the workspace for the ListFeatureClass function
arcpy.env.workspace = r"D:\GIS\ZONE1\ZONE1_007.gdb"
# Use the ListFeatureClasses function to return a list of all FC.
fclist = arcpy.ListFeatureClasses("*","ALL")
# Rename FC
for fc in fclist:
if fc == "TEKST_XX01P_point":
arcpy.Rename_management("TEKST_XX01P_point", "P_XX01_house")
elif fc == "TEKST_XX032_area":
arcpy.Rename_management("TEKST_XX032_area", "A_XX032_forest") The da functionality works if you have access to ArcGIS 10.1 SP1 or higher. If not you may want to read Recursive list feature classes | ArcPy Café. I assume you have access to the da module and what you should read is this post: Inventorying data: a new approach | ArcPy Café (both by the ArcGIS Team Python). A simple example is printing the name (full path) of the featureclass: import os
import arcpy
def inventory_data(workspace, datatypes):
"""
Generates full path names under a catalog tree for all requested
datatype(s).
Parameters:
workspace: string
The top-level workspace that will be used.
datatypes: string | list | tuple
Keyword(s) representing the desired datatypes. A single
datatype can be expressed as a string, otherwise use
a list or tuple. See arcpy.da.Walk documentation
for a full list.
"""
for path, path_names, data_names in arcpy.da.Walk(
workspace, datatype=datatypes):
for data_name in data_names:
yield os.path.join(path, data_name)
for feature_class in inventory_data(r"c:\Forum", "FeatureClass"):
print feature_class From there you can include the logic for renaming the featureclass. Kind regards, Xander
... View more
01-18-2015
09:46 AM
|
1
|
1
|
875
|
|
POST
|
Not sure to which answer you are replying: Jake showed you a tool that in a single run will add the fields POINT_X and POINT_Y to you featureclass Ted showed that you can calculate the fields using Calculate Geometry (use X coordinate of Point for X and Y Coordinate of Point for Y) Joshua offered a method to use a python syntax to fill the fields using the field calculator (!shape.firstPoint.X! for X and !shape.firstPoint.Y! for the Y field). My suggestion has the ability to loop through all the featureclasses in a workspace and add the fields to each of them You will have to decide which method suits your specific needs best.
... View more
01-16-2015
07:04 PM
|
2
|
0
|
15863
|
|
POST
|
It is very similar: def FindLabel ( [LOT] , [SUBDIVISION] ):
return [LOT] + "\n" + [SUBDIVISION]
... View more
01-16-2015
06:02 PM
|
1
|
5
|
5049
|
|
POST
|
Glad it works. If you find it helpful, you may want to mark it as helpful. Kind regards, Xander
... View more
01-16-2015
01:56 PM
|
1
|
24
|
3036
|
|
POST
|
You can also do it automatically with Python as I showed in this post: Automatic X and Y in Attribute Table
... View more
01-16-2015
10:32 AM
|
1
|
0
|
15863
|
|
POST
|
So this is what I came up with (see code below). It creates a table with the following structure: The POL_OID field will be added to the polygons also to allow for a relate. It holds the raster name and the fields for the percentiles. Change this: line 6, point to the raster workspace (it will use all the rasters in that workspace). Remember use only integer rasters! line 7 points to the input polygon feature class line 7 points to the output table that will be created line 10 to 13 contains other settings for percentiles and output fields import arcpy
import os
def main():
# settings
ras_ws = r"C:\Forum\ZonalStatsPercLoop\gdb\Rasters.gdb" # input raster workspace
fc = r"C:\Forum\ZonalStatsPercLoop\gdb\PolygonAndOutput.gdb\polygons" # input polygons
tbl = r"C:\Forum\ZonalStatsPercLoop\gdb\PolygonAndOutput.gdb\ZonalStats5" # output related table
lst_perc = [2, 5, 10, 90, 95, 98] # list of percentiles to be calculated
fld_prefix = "Perc_"
fld_poloid = "POL_OID"
fld_rasname = "RasterName"
# create table
tbl_ws, tbl_name = os.path.split(tbl)
arcpy.CreateTable_management(tbl_ws, tbl_name)
# add fields and fill fields list
flds_tbl = [fld_poloid, fld_rasname]
arcpy.AddField_management(tbl, fld_poloid, "LONG")
arcpy.AddField_management(tbl, fld_rasname, "TEXT", 50)
for perc in lst_perc:
fld_perc = "{0}{1}".format(fld_prefix, perc)
arcpy.AddField_management(tbl, fld_perc, "LONG")
flds_tbl.append(fld_perc)
# Enable Spatial analyst
arcpy.CheckOutExtension("Spatial")
# get list of rasters
lst_ras = getListOfRasterFromWS(ras_ws)
# environments
arcpy.env.workspace = "IN_MEMORY"
arcpy.env.overwriteOutput = True
# create dictionary with polygons OID vs lst_parts
dct_pols = createDictPolygons(fc, fld_poloid)
# start insert cursor for table
with arcpy.da.InsertCursor(tbl, flds_tbl) as curs_tbl:
# start loop through rasters
i = 0
for ras_name in lst_ras:
ras = os.path.join(ras_ws, ras_name)
i += 0
print "Processing Raster '{0}'".format(ras_name)
# loop through polygons
for oid, lst_parts in dct_pols.items():
lst_row = [oid, ras_name]
print " - Processing polygon: {0}".format(oid)
# Execute ExtractByPolygon (you can't send the polygon object)
print " - ExtractByPolygon..."
ras_pol = arcpy.sa.ExtractByPolygon(ras, lst_parts, "INSIDE")
outname = "ras{0}pol{1}".format(i, oid)
ras_pol.save(outname)
print " - saved raster as {0}".format(outname)
# create dictionary with value vs count
print " - fill dict with Value x Count"
flds_ras = ("VALUE", "COUNT")
dct = {row[0]:row[1] for row in arcpy.da.SearchCursor(outname, flds_ras)}
# calculate number of pixels in raster
print " - determine sum"
cnt_sum = sum(dct.values())
print " - sum={0}".format(cnt_sum)
# loop through dictionary and create new dictionary with val vs percentile
print " - create percentile dict"
dct_per = {}
cnt_i = 0
for val in sorted(dct.keys()):
cnt_i += dct[val]
dct_per[val] = cnt_i / cnt_sum
# loop through list of percentiles
print " - iterate percentiles"
for perc in lst_perc:
# use dct_per to determine percentiles
perc_dec = float(perc) / 100
print " - Perc_dec for is {0}".format(perc_dec)
pixval = GetPixelValueForPercentile(dct_per, perc_dec)
print " - Perc for {0}% is {1}".format(perc, pixval)
# write pixel value to percentile field
print " - Store value in list"
# fld_perc = "{0}{1}".format(fld_prefix, perc)
# row[flds.index(fld_perc)] = pixval
lst_row.append(pixval)
# update row
print " - insert row"
row = tuple(lst_row)
curs_tbl.insertRow(row)
# return SA license
arcpy.CheckInExtension("Spatial")
print "Ready..."
def createDictPolygons(fc, fld_poloid):
flds = ("OID@", "SHAPE@", fld_poloid)
# add pol oid field for link
if not FieldExist(fc, fld_poloid):
arcpy.AddField_management(fc, fld_poloid, "LONG")
dct_pols = {}
with arcpy.da.UpdateCursor(fc, flds) as curs:
for row in curs:
oid = row[0]
polygon = row[1]
row[2] = oid
lst_parts = []
if polygon.partCount == 1:
for part in polygon:
for pnt in part:
x, y = pnt.X, pnt.Y
lst_parts.append(arcpy.Point(x, y))
else:
for part in polygon:
lst_crds = []
for pnt in part:
x, y = pnt.X, pnt.Y
lst_crds.append(arcpy.Point(x, y))
lst_parts.append(lst_crds)
# add to dict and store pol oid
dct_pols[oid] = lst_parts
curs.updateRow(row)
return dct_pols
def getListOfRasterFromWS(ras_ws):
arcpy.env.workspace = ras_ws
return arcpy.ListRasters()
def GetPixelValueForPercentile(dctper, percentile):
"""will return last pixel value
where percentile LE searched percentile."""
try:
srt_keys = sorted(dctper.keys())
pix_val = srt_keys[0]
for k in srt_keys:
perc = dctper
if perc <= percentile:
pix_val = k
else:
break
return pix_val
except Exception as e:
print " - GetPixelValueForPercentile error: {0}".format(e)
print "dctper:\n{0}".format(dctper)
return -9999
def FieldExist(featureclass, fieldname):
"""Check if field exists"""
import arcpy
fieldList = arcpy.ListFields(featureclass, fieldname)
return len(fieldList) == 1
if __name__ == '__main__':
main() Have fun! Kind regards, Xander
... View more
01-15-2015
07:36 PM
|
1
|
26
|
3036
|
|
POST
|
Hi Chantell Krider, When you post code, could you please use the syntax highlighting? Posting Code blocks in the new GeoNet In case Dallas answer was helpful you can mark it as Helpfull (below the post you'll find "Helpful Yes | No"). In case Dallas answered your question you can mark his post using the button "Correct Answer". Kind regards, Xander
... View more
01-15-2015
03:47 PM
|
0
|
1
|
1842
|
|
POST
|
In both cases you define or assign (or replace) a coordinate system to a featureclass. The result is the same. The tool however, allows for usage in ModelBuilder and in python scripts (and other coding languages). This way you can automatically apply a coordinate system to multiple featureclasses, while with the manual method (ArcCatalog) you will have to repeat the same process for each featureclass.
... View more
01-15-2015
03:34 PM
|
3
|
0
|
1084
|
|
POST
|
I suppose one could create a related table using the raster value as key so that there can be n raster related to each polygon. It really depends on how you want to use the results.
... View more
01-15-2015
01:02 PM
|
1
|
28
|
3581
|
|
POST
|
You can download the gdb from here: https://www.dropbox.com/l/mfE3IQwXxMO1puq8JAqMSs
... View more
01-15-2015
11:54 AM
|
1
|
0
|
1003
|
|
POST
|
Jake Skinner, could you run a Check Geometry on your resulting featureclass?
... View more
01-15-2015
11:47 AM
|
0
|
0
|
2722
|
|
POST
|
It seems there are only 2000 valid geometries, the rest has null geometry (checked with Check Geometry). I did the same using my code and that does seem to generate the valid geometries. I would have attached the zipped gdb, but it is 116 MB and too large to attach to the thread. If you can provide me with an email address I can send it using wetransfer.com
... View more
01-15-2015
11:36 AM
|
0
|
7
|
2722
|
|
POST
|
This would happen when the percentile you're looking for is higher than the first percentile stored in the dictionary. I guess this could be solved by replacing the def GetPixelValueForPercentile(dctper, percentile) for a slightly changed versión (not tested): def GetPixelValueForPercentile(dctper, percentile):
"""will return last pixel value
where percentile LE searched percentile."""
pix_val = sorted(dctper.keys())[0] # initially assign lowest pixel value
for k in sorted(dctper.keys()):
perc = dctper
if perc <= percentile:
pix_val = k
else:
break
return pix_val
... View more
01-15-2015
10:54 AM
|
1
|
32
|
3581
|
|
POST
|
with Python: the simple way: https://community.esri.com/thread/118781#445348 or using a little more advanced: https://community.esri.com/thread/118781#445572
... View more
01-15-2015
08:47 AM
|
1
|
0
|
3376
|
| Title | Kudos | Posted |
|---|---|---|
| 1 | 01-09-2020 09:26 AM | |
| 6 | 12-20-2019 08:41 AM | |
| 1 | 01-21-2020 07:21 AM | |
| 2 | 01-30-2020 12:46 PM | |
| 1 | 05-30-2019 08:24 AM |
| Online Status |
Offline
|
| Date Last Visited |
3 weeks ago
|