<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: update.da.cursor question about fields in Python Questions</title>
    <link>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1562006#M73236</link>
    <description>&lt;P&gt;Fields are always added to the end.&lt;/P&gt;&lt;P&gt;If you want to get the field names prior to processing you can, and then produce an index to the name.&lt;/P&gt;&lt;P&gt;A simple example&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;fc0 = r'C:\\arcpro_npg\\Project_npg\\tests.gdb\\sq2'
from arcpy.da import SearchCursor
with SearchCursor(fc0, "*") as cursor:
    fld_names = cursor.fields
    n = len(fld_names)
    rpt = list(zip(range(0, n), fld_names))
    print(f"{rpt}")
    for row in cursor:
        print(f'{row[0]}')
        
[(0, 'OBJECTID'), (1, 'Shape'), (2, 'ids'), (3, 'CENTROID_X'),
 (4, 'CENTROID_Y'), (5, 'INSIDE_X'), (6, 'INSIDE_Y'),
 (7, 'PART_COUNT'), (8, 'PNT_COUNT'), (9, 'Sort_'),
 (10, 'Shape_Length'), (11, 'Shape_Area'), (12, 'Text')
, (13, 'Long_'), (14, 'Float_')]
1
2
3
4
5
6
9&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;There is limited information that you can get from the cursor&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;dir(cursor)
['__class__', '__delattr__', '__dir__', '__doc__', '__enter__', '__eq__',
 '__esri_toolinfo__', '__exit__', '__format__', '__ge__', '__getattribute__',
 '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__',
 '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__',
 '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__sizeof__', '__str__', '__subclasshook__',
 '_as_narray', '_dtype',
 'fields', 'next', 'reset']

# -- example
cursor._dtype
dtype([('OBJECTID', '&amp;lt;i4'), ('Shape', '&amp;lt;f8', (2,)), ('ids', '&amp;lt;i4'),
       ('CENTROID_X', '&amp;lt;f8'), ('CENTROID_Y', '&amp;lt;f8'), ('INSIDE_X', '&amp;lt;f8'),
       ('INSIDE_Y', '&amp;lt;f8'), ('PART_COUNT', '&amp;lt;f8'), ('PNT_COUNT', '&amp;lt;f8'),
       ('Sort_', '&amp;lt;i4'), ('Shape_Length', '&amp;lt;f8'), ('Shape_Area', '&amp;lt;f8'),
       ('Text', '&amp;lt;U20'), ('Long_', '&amp;lt;i4'), ('Float_', '&amp;lt;i4')])&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;the _as_narray can't be used if the fields includes the geometry, in such cases, you can use arcpy's FeatureClassToNumPyArray or TableToNumPyArray&lt;/P&gt;</description>
    <pubDate>Sun, 24 Nov 2024 10:32:54 GMT</pubDate>
    <dc:creator>DanPatterson</dc:creator>
    <dc:date>2024-11-24T10:32:54Z</dc:date>
    <item>
      <title>update.da.cursor question about fields</title>
      <link>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1561993#M73235</link>
      <description>&lt;P&gt;Hi everyone,&lt;/P&gt;&lt;P&gt;I'm stuck on a situation that I feel I'm making more complicated than it needs to be.&lt;/P&gt;&lt;P&gt;Situation:&amp;nbsp;&lt;/P&gt;&lt;P&gt;I have a database (700K records) that updates daily, I convert it to a spatial dataframe. I have a hosted feature layer (points) that updates daily. Right now I truncate and append the entire thing, but having it empty for a while isn't ideal.&lt;/P&gt;&lt;P&gt;I want to basically this:&lt;/P&gt;&lt;UL&gt;&lt;LI&gt;For each row in the database, search for the same 'key' in the hosted.&lt;/LI&gt;&lt;LI&gt;If return clause = 1&lt;/LI&gt;&lt;LI&gt;If any of the fields have different values, then update that field (or just the entire row)&lt;/LI&gt;&lt;LI&gt;else&amp;nbsp;&lt;/LI&gt;&lt;LI&gt;If return clause = 0&lt;/LI&gt;&lt;LI&gt;insert cursor to insert that row&lt;/LI&gt;&lt;LI&gt;else next row&lt;/LI&gt;&lt;/UL&gt;&lt;P&gt;Where I am getting confused is, does the da.cursor just use field position to insert values? row[19] will update the 19th column. But what if someone inserts a new column in the database, would everything get screwed up? Can I instead just match the field names with a field map?&lt;/P&gt;</description>
      <pubDate>Sun, 24 Nov 2024 01:40:54 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1561993#M73235</guid>
      <dc:creator>CW-GIS</dc:creator>
      <dc:date>2024-11-24T01:40:54Z</dc:date>
    </item>
    <item>
      <title>Re: update.da.cursor question about fields</title>
      <link>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1562006#M73236</link>
      <description>&lt;P&gt;Fields are always added to the end.&lt;/P&gt;&lt;P&gt;If you want to get the field names prior to processing you can, and then produce an index to the name.&lt;/P&gt;&lt;P&gt;A simple example&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;fc0 = r'C:\\arcpro_npg\\Project_npg\\tests.gdb\\sq2'
from arcpy.da import SearchCursor
with SearchCursor(fc0, "*") as cursor:
    fld_names = cursor.fields
    n = len(fld_names)
    rpt = list(zip(range(0, n), fld_names))
    print(f"{rpt}")
    for row in cursor:
        print(f'{row[0]}')
        
[(0, 'OBJECTID'), (1, 'Shape'), (2, 'ids'), (3, 'CENTROID_X'),
 (4, 'CENTROID_Y'), (5, 'INSIDE_X'), (6, 'INSIDE_Y'),
 (7, 'PART_COUNT'), (8, 'PNT_COUNT'), (9, 'Sort_'),
 (10, 'Shape_Length'), (11, 'Shape_Area'), (12, 'Text')
, (13, 'Long_'), (14, 'Float_')]
1
2
3
4
5
6
9&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;There is limited information that you can get from the cursor&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;dir(cursor)
['__class__', '__delattr__', '__dir__', '__doc__', '__enter__', '__eq__',
 '__esri_toolinfo__', '__exit__', '__format__', '__ge__', '__getattribute__',
 '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__',
 '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__',
 '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__sizeof__', '__str__', '__subclasshook__',
 '_as_narray', '_dtype',
 'fields', 'next', 'reset']

# -- example
cursor._dtype
dtype([('OBJECTID', '&amp;lt;i4'), ('Shape', '&amp;lt;f8', (2,)), ('ids', '&amp;lt;i4'),
       ('CENTROID_X', '&amp;lt;f8'), ('CENTROID_Y', '&amp;lt;f8'), ('INSIDE_X', '&amp;lt;f8'),
       ('INSIDE_Y', '&amp;lt;f8'), ('PART_COUNT', '&amp;lt;f8'), ('PNT_COUNT', '&amp;lt;f8'),
       ('Sort_', '&amp;lt;i4'), ('Shape_Length', '&amp;lt;f8'), ('Shape_Area', '&amp;lt;f8'),
       ('Text', '&amp;lt;U20'), ('Long_', '&amp;lt;i4'), ('Float_', '&amp;lt;i4')])&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;the _as_narray can't be used if the fields includes the geometry, in such cases, you can use arcpy's FeatureClassToNumPyArray or TableToNumPyArray&lt;/P&gt;</description>
      <pubDate>Sun, 24 Nov 2024 10:32:54 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1562006#M73236</guid>
      <dc:creator>DanPatterson</dc:creator>
      <dc:date>2024-11-24T10:32:54Z</dc:date>
    </item>
    <item>
      <title>Re: update.da.cursor question about fields</title>
      <link>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1562162#M73237</link>
      <description>&lt;P&gt;&lt;a href="https://community.esri.com/t5/user/viewprofilepage/user-id/471024"&gt;@CW-GIS&lt;/a&gt;&amp;nbsp;you can use the &lt;A href="https://pro.arcgis.com/en/pro-app/latest/tool-reference/data-management/append.htm" target="_self"&gt;Append&lt;/A&gt; tool and perform an &lt;A href="https://www.esri.com/arcgis-blog/products/arcgis-pro/analytics/upsert-your-datasets-using-the-append-tool-in-arcgis-pro-3-1/" target="_self"&gt;upsert&lt;/A&gt; by specifying &lt;A href="https://pro.arcgis.com/en/pro-app/latest/tool-reference/data-management/append.htm#:~:text=SQL%20Expression-,match_fields,-%5B%5Btarget_field%2C%20input_field%5D%2C...%5D" target="_self"&gt;match fields&lt;/A&gt;.&lt;/P&gt;</description>
      <pubDate>Mon, 25 Nov 2024 11:57:58 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1562162#M73237</guid>
      <dc:creator>JakeSkinner</dc:creator>
      <dc:date>2024-11-25T11:57:58Z</dc:date>
    </item>
    <item>
      <title>Re: update.da.cursor question about fields</title>
      <link>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1562247#M73240</link>
      <description>&lt;P&gt;Here is something I use daily to insert missing features.&lt;/P&gt;&lt;LI-CODE lang="c"&gt;import arcpy

# Paths to your database and hosted feature layer
database_path = "database"
hosted_layer_url = "feature_layer"

# Define the fields to be used
fields = ['unique_id', 'other_field', 'field1', 'field2', 'field3']  # Add all necessary fields here

# Count the number of features before the insert
initial_feature_count = int(arcpy.GetCount_management(hosted_layer).getOutput(0))
print(f"Initial number of features: {initial_feature_count}")

# Create a dictionary of database records for quick lookup
database_records = {}
with arcpy.da.SearchCursor(database_path, fields) as search_cursor:
    for row in search_cursor:
        unique_id = row[fields.index('unique_id')]
        database_records[unique_id] = row

update_count = 0
insert_count = 0

# Update or insert rows
with arcpy.da.UpdateCursor(hosted_layer, fields) as update_cursor:
    for row in update_cursor:
        unique_id = row[fields.index('unique_id')]
        if unique_id in database_records:
            matching_row = database_records[unique_id]
            # Check if any fields have different values
            updated = False
            for i, field in enumerate(fields):
                if row[i] != matching_row[i]:
                    row[i] = matching_row[i]
                    updated = True
            if updated:
                update_cursor.updateRow(row)
                update_count += 1
        else:
            # Insert new row if unique_id is not found
            with arcpy.da.InsertCursor(hosted_layer, fields) as insert_cursor:
                insert_cursor.insertRow(database_records[unique_id])
                insert_count += 1

# Count the number of features after the insert
final_feature_count = int(arcpy.GetCount_management(hosted_layer).getOutput(0))
print(f"Final number of features: {final_feature_count}")
print(f"Number of features updated: {update_count}")
print(f"Number of features inserted: {insert_count}")

print("Update and insert operations completed.")&lt;/LI-CODE&gt;</description>
      <pubDate>Mon, 25 Nov 2024 15:58:46 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1562247#M73240</guid>
      <dc:creator>TonyAlmeida</dc:creator>
      <dc:date>2024-11-25T15:58:46Z</dc:date>
    </item>
    <item>
      <title>Re: update.da.cursor question about fields</title>
      <link>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1564675#M73273</link>
      <description>&lt;P&gt;&lt;a href="https://community.esri.com/t5/user/viewprofilepage/user-id/3265"&gt;@TonyAlmeida&lt;/a&gt;&amp;nbsp;&amp;nbsp; Thank you! This works.&amp;nbsp;&lt;/P&gt;&lt;P&gt;I'm confused though, I run it once and I see it changes the values. If I run it a second time, 10 minutes later, shouldn't there be no edits because everything has already been edited to match the database?&amp;nbsp;&lt;/P&gt;&lt;P&gt;When I run in 10 minutes later, it still makes the same number of changes as the first run.&lt;/P&gt;</description>
      <pubDate>Wed, 04 Dec 2024 19:42:23 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1564675#M73273</guid>
      <dc:creator>CW-GIS</dc:creator>
      <dc:date>2024-12-04T19:42:23Z</dc:date>
    </item>
    <item>
      <title>Re: update.da.cursor question about fields</title>
      <link>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1564692#M73275</link>
      <description>&lt;P&gt;Although Esri supports "*" for fields with ArcPy DA cursors, they did so reluctantly, and it is a bad practice.&amp;nbsp; You should always explicitly list the fields in a cursor, then you always know the order regardless of the order of the fields in the table.&lt;/P&gt;</description>
      <pubDate>Wed, 04 Dec 2024 15:30:54 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1564692#M73275</guid>
      <dc:creator>JoshuaBixby</dc:creator>
      <dc:date>2024-12-04T15:30:54Z</dc:date>
    </item>
    <item>
      <title>Re: update.da.cursor question about fields</title>
      <link>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1565181#M73281</link>
      <description>&lt;P&gt;Your right, mine does the same. Try this.&lt;/P&gt;&lt;P&gt;Changes made are:&lt;/P&gt;&lt;P&gt;1- Trimmed whitespace and converted all field values to strings before comparison&lt;/P&gt;&lt;P&gt;2 - Prevents redundant inserts by comparing existing unique IDs in the hosted layer&lt;/P&gt;&lt;LI-CODE lang="c"&gt;import arcpy

# Paths to the local database and the hosted feature layer
database_path = "database"
hosted_layer = "feature_layer"

# Fields to check and update
fields = ['unique_id', 'other_field', 'field1', 'field2', 'field3']  # Update this list as needed

# Get the initial count of features in the hosted layer
initial_feature_count = int(arcpy.GetCount_management(hosted_layer).getOutput(0))
print(f"Initial number of features: {initial_feature_count}")

# Create a dictionary to store records from the database for quick lookups
database_records = {}
with arcpy.da.SearchCursor(database_path, fields) as search_cursor:
    for row in search_cursor:
        unique_id = row[fields.index('unique_id')]
        database_records[unique_id] = row

update_count = 0
insert_count = 0

# Process rows in the hosted layer to update existing records
with arcpy.da.UpdateCursor(hosted_layer, fields) as update_cursor:
    for row in update_cursor:
        unique_id = row[fields.index('unique_id')]
        if unique_id in database_records:
            matching_row = database_records[unique_id]
            updated = False
            # Compare each field and update values if they differ
            for i, field in enumerate(fields):
                if str(row[i]).strip() != str(matching_row[i]).strip():
                    row[i] = matching_row[i]
                    updated = True
            if updated:
                update_cursor.updateRow(row)
                update_count += 1

# Insert new rows for records in the database that are not in the hosted layer
with arcpy.da.SearchCursor(hosted_layer, ['unique_id']) as hosted_cursor:
    hosted_ids = {row[0] for row in hosted_cursor}

for unique_id, record in database_records.items():
    if unique_id not in hosted_ids:
        with arcpy.da.InsertCursor(hosted_layer, fields) as insert_cursor:
            insert_cursor.insertRow(record)
            insert_count += 1

# Get the final count of features in the hosted layer
final_feature_count = int(arcpy.GetCount_management(hosted_layer).getOutput(0))
print(f"Final number of features: {final_feature_count}")
print(f"Number of features updated: {update_count}")
print(f"Number of features inserted: {insert_count}")

print("Update and insert operations completed.")&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Thu, 05 Dec 2024 16:05:08 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/update-da-cursor-question-about-fields/m-p/1565181#M73281</guid>
      <dc:creator>TonyAlmeida</dc:creator>
      <dc:date>2024-12-05T16:05:08Z</dc:date>
    </item>
  </channel>
</rss>

