|
POST
|
I am on 3.7, but I was not able to get past the ,from arcpy.typing.describe import FeatureClass. The issue ended up being the Shape@ and Legnth fields. For some reason they were not calculated correctly in the File Geodatabase. So my code did work by updating the NewIDField.
... View more
08-01-2024
07:19 AM
|
1
|
1
|
3021
|
|
POST
|
Yes, I did know that, which is why I am trying to populate the new filed "NewIDField". I am still having issue with the sort.
... View more
07-26-2024
11:08 AM
|
0
|
1
|
3153
|
|
POST
|
I am need to reorder the objectID, but I am having difficulties getting the code correct. The OriginalOrder.png is what it currently is and the ReOrder.png is what I want. see pictures. I need the reorder to match the ReOrder picture. code, import arcpy
# Define paths
input_fc = r"C:\Temp\Grid.gdb\Clipped_Grid_Polygons"
# Add fields for Max_Longitude and Min_Latitude if they don't already exist
fields = [f.name for f in arcpy.ListFields(input_fc)]
if "Max_Longitude" not in fields:
arcpy.AddField_management(input_fc, "Max_Longitude", "DOUBLE")
if "Min_Latitude" not in fields:
arcpy.AddField_management(input_fc, "Min_Latitude", "DOUBLE")
if "NewIDField" not in fields:
arcpy.AddField_management(input_fc, "NewIDField", "LONG")
# Calculate Max_Longitude and Min_Latitude for each feature
with arcpy.da.UpdateCursor(input_fc, ["OBJECTID", "SHAPE@", "Max_Longitude", "Min_Latitude"]) as cursor:
for row in cursor:
polygon = row[1]
max_longitude = max(point.X for part in polygon for point in part)
min_latitude = min(point.Y for part in polygon for point in part)
row[2] = max_longitude
row[3] = min_latitude
cursor.updateRow(row)
print("Max_Longitude and Min_Latitude fields calculated and updated.")
# Extract the features into a list
features = []
with arcpy.da.SearchCursor(input_fc, ["OBJECTID", "Max_Longitude", "Min_Latitude"]) as cursor:
for row in cursor:
features.append((row[0], row[1], row[2]))
# Sort the list based on Min_Latitude (ascending) and Max_Longitude (descending)
features.sort(key=lambda x: (x[2], -x[1]))
# Create a dictionary to map the new OID values
new_oid_mapping = {oid_tuple[0]: index + 1 for index, oid_tuple in enumerate(features)}
# Update the original feature class with the new NewIDField values based on the sorted order
with arcpy.da.UpdateCursor(input_fc, ["OBJECTID", "NewIDField"]) as cursor:
for row in cursor:
current_oid = row[0]
if current_oid in new_oid_mapping:
row[1] = new_oid_mapping[current_oid]
cursor.updateRow(row)
print("NewIDField values reordered based on Min_Latitude and Max_Longitude sorting.")
... View more
07-26-2024
09:38 AM
|
1
|
6
|
3184
|
|
POST
|
I have some fields that I need to remove the # and numbers, but I need to keep one that matches exactly HIGHWAY DISTRICT #4. I can't seem to get to bypass "HIGHWAY DISTRICT #4". When I run my code, it removes the #4 from HIGHWAY DISTRICT #4 import arcpy
import time
fc3 = r"C:\Default.gdb\Table_1"
fld = ['FireDist', 'HighwayDist', 'SchoolDist']
def dump_stuff(val):
"""Remove unwanted characters from fields except 'HIGHWAY DISTRICT #4'"""
if isinstance(val, str):
if val.strip() == "HIGHWAY DISTRICT #4":
return val # Keep "HIGHWAY DISTRICT #4" unchanged
else:
return "".join([i for i in val if not (i.isdigit() or i == '#')])
return val
start_time = time.time() # Record the start time
with arcpy.da.UpdateCursor(fc3, fld) as cursor:
for row in cursor:
# Process each field in the row
new_row = [dump_stuff(val) for val in row]
cursor.updateRow(new_row)
end_time = time.time() # Record the end time
elapsed_time = end_time - start_time
minutes, seconds = divmod(elapsed_time, 60)
print(f"Process time: {int(minutes)} minutes {int(seconds)} seconds")
... View more
06-14-2024
11:03 AM
|
0
|
2
|
1003
|
|
POST
|
Thanks for the reply. I was coming back to my post to add code that worked for me. try:
# Update the street names in the table
with arcpy.da.UpdateCursor(table, "STREET") as cursor:
for row in cursor:
street_name = row[0]
# List of common street prefixes to be removed
prefixes = ['N ', 'S ', 'E ', 'W ', 'North ', 'South ', 'East ', 'West ']
# Remove prefixes from the street name
for prefix in prefixes:
if street_name.startswith(prefix):
row[0] = street_name[len(prefix):].strip()
cursor.updateRow(row)
break Your code did work tho. Again thanks for the reply!
... View more
01-08-2024
09:44 AM
|
1
|
2
|
3404
|
|
POST
|
I am trying to remove prefixes from a table. I have the following code but it removes more than just street prefix. I my code I have E "space", "E ". I need to be able to strip the prefixes so I can sort, then delete duplicates. How can I remove just the prefixes? with arcpy.da.UpdateCursor(table1,'STREET') as cursor:
for row in cursor:
#print row[0]
if row[0].startswith("S "):
#print "Deleting S"
row [0] = row[0].lstrip('S ')
elif row[0].startswith("E "):
#print "Deleting E"
row [0] = row[0].lstrip('E ')
elif row[0].startswith("W "):
#print "Deleting W"
row [0] = row[0].lstrip('W ')
elif row[0].startswith("N "):
#print "Deleting N"
row [0] = row[0].lstrip('N ')
cursor.updateRow(row)
del cursor After code runs i get. Before Code After code E Explorer xplorer E Expedition xpedtion E Exective xecutive E Exchange xchange
... View more
01-08-2024
08:57 AM
|
0
|
6
|
3473
|
|
POST
|
I was able to accomplish what I needed with the following. PR = "PrivateRoads"
CityLimits = 'City_Limits'
arcpy.MakeFeatureLayer_management(PR, "polyLyr")
arcpy.MakeFeatureLayer_management(CityLimits, "CitLyr")
unique_strings = []
with arcpy.da.SearchCursor("CitLyr", 'CITY') as cursor:
for row in cursor:
unique_strings.append(row[0])
#print (unique_strings)
for unique in unique_strings:
arcpy.SelectLayerByAttribute_management("CitLyr", 'NEW_SELECTION', "CITY = '{}'".format(unique))
arcpy.SelectLayerByLocation_management("polyLyr", 'HAVE_THEIR_CENTER_IN', "CitLyr", "", "NEW_SELECTION")
with arcpy.da.UpdateCursor(PR, 'Owner') as cursor:
for row in cursor:
row[0] = unique
cursor.updateRow(row)
... View more
07-13-2023
10:56 AM
|
0
|
0
|
1366
|
|
POST
|
I tried the following but the print only prints one of the cities and for some reason it's populates only a a few private roads that are not inside city limits. Some of these will not be in a city. I honestly thought it would simple and wouldn't' involve .keys or dicts. import sys, os, arcpy
arcpy.env.overwriteOutput = True
workspace = "C:/temp/temp.gdb"
PR = "PrivateRoads"
CityLimits = 'City_Limits'
arcpy.MakeFeatureLayer_management(PR, "polyLyr")
arcpy.MakeFeatureLayer_management(CityLimits, "CitLyr")
arcpy.management.SelectLayerByLocation("polyLyr", "HAVE_THEIR_CENTER_IN", "CitLyr", "", "NEW_SELECTION")
pr_oid_to_city_name = dict()
# Add code here to use a search cursor to scan the polyLyr and
# populate the dict that maps the pr OID to the city name
with arcpy.da.SearchCursor("CitLyr", ['OID@', 'CITY']) as search_cursor:
for oid, city_name in search_cursor:
pr_oid_to_city_name[oid] = city_name
print(pr_oid_to_city_name[oid])
# Start an edit session. Must provide the workspace.
edit = arcpy.da.Editor(workspace)
# Edit session is started without an undo/redo stack for versioned data
# (for the second argument, use False for unversioned data)
edit.startEditing(True)
# Start an edit operation
edit.startOperation()
fields = ['OID@', 'Owner']
with arcpy.da.UpdateCursor(PR, fields) as cursor:
for row in cursor:
oid = row[0]
if oid in pr_oid_to_city_name:
row[1] = pr_oid_to_city_name[oid]
cursor.updateRow(row)
edit.stopOperation()
# Stop the edit session and save the changes
edit.stopEditing(True)
... View more
07-12-2023
03:13 PM
|
0
|
0
|
1383
|
|
POST
|
I need to update the PrivateRoads 'Owner' field based on what city the private road is in. I have the following but it take for ever but doesn't populate the correct city. I know I can do a spatial join but I don't want to create a separate layer. import sys, os, arcpy
import arcpy
## Works in file geodatabase
arcpy.env.overwriteOutput = True
workspace = "C:/temp/temp.gdb"
PR = "PrivateRoads"
CityLimits = 'City_Limits'
arcpy.MakeFeatureLayer_management(PR, "polyLyr")
arcpy.MakeFeatureLayer_management(CityLimits, "CitLyr")
with arcpy.da.UpdateCursor(PR, ['SHAPE@', 'OID@', 'Owner']) as cursor:
for row in cursor:
arcpy.management.SelectLayerByLocation("polyLyr", "HAVE_THEIR_CENTER_IN", "CitLyr", "", "NEW_SELECTION")
with arcpy.da.SearchCursor("CitLyr", ['CITY']) as cCursor:
for cRow in cCursor:
row[2] = cRow[0]
cursor.updateRow(row)
... View more
07-11-2023
01:15 PM
|
0
|
3
|
1459
|
|
POST
|
I tried to incorporate you suggestion, but I ran into an issue with the Global ID. At least I believe that is the issue. TypeError: sequence size must match size of the row. import arcpy, os
project = arcpy.mp.ArcGISProject("CURRENT")
arcpy.env.workspace = os.path.dirname(project.filePath)
wp = os.path.dirname(project.filePath)
outPath = r'C:\Temp\Scratchworkspace.gdb'
scr = 'SUBS'
sortedTableName = 'SUBS_ordered'
arcpy.management.MakeFeatureLayer("SUBS", "memory\SubsLyr")
arcpy.SelectLayerByLocation_management("SUBS", "WITHIN_A_DISTANCE", "SUBJECT_PROPERTY", "1 Mile", "NEW_SELECTION")
arcpy.analysis.Select("SUBS", r"memory/SubLayer1")
#--check if output feature class exists, if not, create it
if not os.path.exists(os.path.join(outPath,sortedTableName)):
out_fc = arcpy.management.CreateFeatureclass(outPath,out_name="SUBS_ordered", template=scr)
else:
try:
arcpy.DeleteRows_management(os.path.join(outPath,"SUBS_ordered"))
except:
pass
source_fc = r"memory/SubLayer1"
sort_field_name = "SUB_NAME"
source_fc_fields = [f.name for f in arcpy.ListFields(scr)]
with arcpy.da.SearchCursor(source_fc, "*", sql_clause=(None, f"ORDER BY {sort_field_name}")) as s_cursor:
with arcpy.da.InsertCursor(sortedTableName, "*") as i_cursor:
for row in s_cursor:
i_cursor.insertRow(row) The "SUBS" is in SDE geodatabase and has GlobalID . The "SUBS_ordered" in a file geodatabase doesn't have a GlobalID. How can I leave out the GlobalID or other fields? The other difference between the two is. SubLayer1: Shape_STArea__ , Shape_STLength__ SUBS_ordered : Shape_Area, Shape_Length
... View more
05-25-2023
10:52 AM
|
0
|
1
|
1077
|
|
POST
|
Sorry, it derived from a feature class in a geodatabase. I preform a selection by location, then I export the selected features to the shapefile.
... View more
05-19-2023
01:38 PM
|
0
|
3
|
1097
|
|
POST
|
I will take your advice and create it in a geodatabase.
... View more
05-19-2023
11:41 AM
|
0
|
5
|
2763
|
|
POST
|
That .dbf of that shapefile is using in a different reporting system. I was trying to save having to manually sort every time the .dbf is used. I run this reporting once a day or sometimes more often.
... View more
05-19-2023
07:26 AM
|
0
|
9
|
2779
|
|
POST
|
Blake, this is helpful but it doesn't physically change the order of the SUB_NAME field. I have the following and it does sort the SUB_NAME field of the shapefile but somehow it spatially moves the features, not sure why. Would it best to place this shapefile in to a file geodatabase? fc = 'C:\Temp\SUBS.shp'
datatosort = []
with arcpy.da.SearchCursor(fc,"*") as cursor:
for row in cursor:
datatosort.append(row)
subindex = 2
rowindex = 0
datatosort.sort(key=lambda tup: tup[subindex])
with arcpy.da.UpdateCursor(fc,"*") as cursor:
for row in cursor:
row = datatosort[rowindex]
rowindex += 1
cursor.updateRow(row)
... View more
05-17-2023
09:47 AM
|
0
|
11
|
2798
|
| Title | Kudos | Posted |
|---|---|---|
| 1 | 08-01-2024 07:19 AM | |
| 1 | 07-26-2024 09:38 AM | |
| 1 | 01-08-2024 09:44 AM | |
| 1 | 03-07-2023 11:46 AM | |
| 1 | 11-02-2020 08:24 AM |
| Online Status |
Offline
|
| Date Last Visited |
02-12-2026
12:36 PM
|