<?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: Arcpy Script to loop through field and run Union Analysis in Python Questions</title>
    <link>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153674#M64055</link>
    <description>&lt;P&gt;beat it up for hourS.&amp;nbsp; sql...ugh. this seemed to work.&amp;nbsp; thanks much for your help put in the right direction&lt;/P&gt;&lt;LI-CODE lang="python"&gt;try:
    for year in unique_year:
        for gear in unique_gear:
            selectionClause = '{0} = {1}'.format('YEAR', year) + str(" AND ") + '{0} = '"'{1}'"''.format('AGENCY_GEAR',gear)
            new_layer = str(year) + str(gear) 
            arcpy.MakeFeatureLayer_management(trawlBuffs, new_layer)
            arcpy.SelectLayerByAttribute_management(new_layer, "NEW_SELECTION", selectionClause)
            out_feat = unionOut + str(year) + str(gear)        
            arcpy.Union_analysis([fishnet, new_layer], out_feat)
            print("Writing Data File: " + out_feat)
except Exception as e:
    #dump errors
    print("Error: " + e.args[0]) 
finally:
    #Clean up the temp layer
    arcpy.Delete_management(new_layer)&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
    <pubDate>Tue, 15 Mar 2022 06:43:40 GMT</pubDate>
    <dc:creator>ssintelmann</dc:creator>
    <dc:date>2022-03-15T06:43:40Z</dc:date>
    <item>
      <title>Arcpy Script to loop through field and run Union Analysis</title>
      <link>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153509#M64046</link>
      <description>&lt;P&gt;&lt;SPAN&gt;&amp;nbsp;&lt;/SPAN&gt;have a polygon file in form of a fishnet. Also another feature class with polygons named Trawl_Buffers. There is a unique field within Trawl_Buffers based on YEAR. I'd like to create a script to run a selection on YEAR, and then perform a union analysis with the fishnet polygon for each YEAR. So the desired output would be "Trawl_Buffers_union2003", "Trawl_Buffers_union2004" etc. I have a function that will get me the unique list of the years, and puts them in a list which i called vals.&lt;/P&gt;&lt;P&gt;Then seems I need to run a for loop over this list of unique years, create a temporary selection, then use that as input for the union, but I am having trouble implementing the query process.&lt;/P&gt;&lt;P&gt;Here is where I started, but seriously tripping:&lt;/P&gt;&lt;PRE&gt;import arcpy
 
#Set the data environment 
arcpy.env.overwriteOutput = True

arcpy.env.workspace = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb'
trawlBuffs = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb\buffers\buffers_testing'
fishnet = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb\fishnets\vms_net1k'
unionOut = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb\unions\union'

# function to get unique values for the YEAR field found within the trawlBuffs fc
def unique_values(table, field):
    with arcpy.da.SearchCursor(table, [field]) as cursor:
        return sorted({row[0] for row in cursor})

# Get the unique values for the field 'YEAR' found within the 'trawl_buffs' featureclass table
vals = unique_values(trawlBuffs, "YEAR")

# Create a query string for the selected country
yearSelectionClause = '"YEAR" = ' + "'" + vals + "'"

#loop through the years, create selection, union, make permanent
for year in vals:
    year_layer = str(year) + "_union"
    arcpy.MakeFeatureLayer_management(trawlBuffs, year_layer)
    arcpy.SelectLayerByAttribute_management(year_layer, "NEW_SELECTION", "\"YEAR"\" = %d" % (year))
    arcpy.Union_analysis(fishnet, year_layer , unionOut)
    arcpy.CopyFeatures_management(year_layer, "union_" + str(year))&lt;/PRE&gt;</description>
      <pubDate>Mon, 14 Mar 2022 20:09:15 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153509#M64046</guid>
      <dc:creator>ssintelmann</dc:creator>
      <dc:date>2022-03-14T20:09:15Z</dc:date>
    </item>
    <item>
      <title>Re: Arcpy Script to loop through field and run Union Analysis</title>
      <link>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153550#M64047</link>
      <description>&lt;LI-CODE lang="python"&gt;import arcpy
 
#Set the data environment 
arcpy.env.overwriteOutput = True

arcpy.env.workspace = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb'
trawlBuffs = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb\buffers\buffers_testing'
fishnet = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb\fishnets\vms_net1k'
unionOut = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb\unions\union_'

# function to get unique values for the YEAR field found within the trawlBuffs fc
#how is this unique? just a sorted list of every value - and why sort it?
def unique_values(table, field):
    with arcpy.da.SearchCursor(table, [field]) as cursor:
        return sorted({row[0] for row in cursor})

# Get the unique values for the field 'YEAR' found within the 'trawl_buffs' featureclass table
vals = unique_values(trawlBuffs, "YEAR")
#a set would be unique
unique_vals = set(vals)

# Create a query string for the selected country
#vals is a list??
#yearSelectionClause = '"YEAR" = ' + "'" + vals + "'"

#loop through the years, create selection, union, make permanent
#your clause goes in the loop instead
for year in unique_vals:
    #not sure if year is text or number?? this affects the query
    #if number
    yearSelectionClause = '{0} = {1}'.format('YEAR',year)
    #if string
    #yearSelectionClause = '{0} = "{1}"'.format('YEAR',year)
    
    year_layer = str(year) + "_union"
    arcpy.MakeFeatureLayer_management(trawlBuffs, year_layer)
    #i have no idea what this is
    #arcpy.SelectLayerByAttribute_management(year_layer, "NEW_SELECTION", "\"YEAR"\" = %d" % (year))
    arcpy.SelectLayerByAttribute_management(year_layer, "NEW_SELECTION", yearSelectionClause)

    #should be a list of input??
    #unionOut will just overwrite itself
    #arcpy.Union_analysis(fishnet, year_layer , unionOut)

    out_feat = unionOut + str(year)
    arcpy.Union_analysis([fishnet, year_layer] , out_feat)

    #why?
    #arcpy.CopyFeatures_management(year_layer, "union_" + str(year))&lt;/LI-CODE&gt;</description>
      <pubDate>Mon, 14 Mar 2022 20:58:05 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153550#M64047</guid>
      <dc:creator>DavidPike</dc:creator>
      <dc:date>2022-03-14T20:58:05Z</dc:date>
    </item>
    <item>
      <title>Re: Arcpy Script to loop through field and run Union Analysis</title>
      <link>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153556#M64048</link>
      <description>&lt;P&gt;Hard to really say without seeing the data, or at least what "seriously tripping" means (I.e., what error are you getting).&lt;/P&gt;&lt;P&gt;But, in this line:&lt;/P&gt;&lt;LI-CODE lang="python"&gt;yearSelectionClause = '"YEAR" = ' + "'" + vals + "'"&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;you are trying to concatenate a string to a list object, and will error out.&amp;nbsp;&lt;/P&gt;&lt;P&gt;Plus, I don't see anywhere that yearSelectionClause is being used anyway.&lt;/P&gt;&lt;P&gt;Suspect you want to move that into the loop, and replace the clause in the SelectLayer line.&lt;/P&gt;&lt;P&gt;Something like this (which is now using the year from the vals list, not the entire list):&lt;/P&gt;&lt;LI-CODE lang="python"&gt;for year in vals:
    yearSelectionClause = '"YEAR" = ' + "'" + year + "'"
    year_layer = str(year) + "_union"
    arcpy.MakeFeatureLayer_management(trawlBuffs, year_layer)
    arcpy.SelectLayerByAttribute_management(year_layer, "NEW_SELECTION",yearSelectionClause)&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;You might even be able to skip the SelectBy line and just put the where clause in the makefeaturelayer:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;arcpy.management.MakeFeatureLayer(trawlBuffs, year_layer, yearSelectionClause)&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;R_&lt;/P&gt;</description>
      <pubDate>Mon, 14 Mar 2022 21:08:25 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153556#M64048</guid>
      <dc:creator>RhettZufelt</dc:creator>
      <dc:date>2022-03-14T21:08:25Z</dc:date>
    </item>
    <item>
      <title>Re: Arcpy Script to loop through field and run Union Analysis</title>
      <link>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153572#M64049</link>
      <description>&lt;P&gt;Thank you for straightening me out, I appreciate it.&amp;nbsp; For my own help, could you kindly explain what is actually going on in Line 31 of your code?&amp;nbsp; The rest is clear for me.&amp;nbsp;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Mon, 14 Mar 2022 21:42:02 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153572#M64049</guid>
      <dc:creator>ssintelmann</dc:creator>
      <dc:date>2022-03-14T21:42:02Z</dc:date>
    </item>
    <item>
      <title>Re: Arcpy Script to loop through field and run Union Analysis</title>
      <link>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153581#M64051</link>
      <description>&lt;P&gt;I would look at the .format python method, I would just print that line with some dummy values in a new script to see how it works.&amp;nbsp; Personally I find .format() simplifies building these where clauses which can get a bit convoluted with single, double even triple quotes.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;essentially the printed statement should look like how it would appear if created in the select by attributes GUI&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Mon, 14 Mar 2022 22:11:18 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153581#M64051</guid>
      <dc:creator>DavidPike</dc:creator>
      <dc:date>2022-03-14T22:11:18Z</dc:date>
    </item>
    <item>
      <title>Re: Arcpy Script to loop through field and run Union Analysis</title>
      <link>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153608#M64053</link>
      <description>&lt;P&gt;ahhh, I think I get it, basically {} are indexes it seems.&amp;nbsp; Soooo, taking what you worked out, what if I wanted to take it a step further and instead create a new unique union feature for each YEAR, like above but ALSO on another string field entitled "AGENCY_GEAR".&amp;nbsp; So output files would be:&lt;/P&gt;&lt;P&gt;gear1_2003_union&lt;/P&gt;&lt;P&gt;gear2_2003_union&lt;/P&gt;&lt;P&gt;gear1_2004_union&lt;/P&gt;&lt;P&gt;gear2_2004_union, etc&lt;/P&gt;&lt;P&gt;Would you nest for loops, separate selection clause, or combined selection clause ?&amp;nbsp; Aimlessly stabbed below, where I used the same function to gather unique values of the AGENCY_GEAR.:&lt;/P&gt;&lt;P&gt;import arcpy&lt;BR /&gt;&lt;BR /&gt;#Set the data environment&lt;BR /&gt;arcpy.env.overwriteOutput = True&lt;/P&gt;&lt;P&gt;arcpy.env.workspace = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb'&lt;BR /&gt;trawlBuffs = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb\buffers\buff_test_subset'&lt;BR /&gt;fishnet = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb\fishnets\vms_net1k'&lt;BR /&gt;unionOut = r'C:\Data\working\AK_Fishing_VMS\2021_Delivery\ArcPro_proj\ArcPro_proj.gdb\unions\union'&lt;/P&gt;&lt;P&gt;# function to get unique values for the YEAR field found within the trawlBuffs fc&lt;BR /&gt;def unique_values(table, field):&lt;BR /&gt;with arcpy.da.SearchCursor(table, [field]) as cursor:&lt;BR /&gt;return sorted({row[0] for row in cursor})&lt;BR /&gt;# Get the unique values for the field 'YEAR' found within the 'trawl_buffs' featureclass table&lt;BR /&gt;yearVals = unique_values(trawlBuffs, "YEAR")&lt;BR /&gt;unique_year = set(yearVals)&lt;BR /&gt;# Get the unique values for the field 'AGENCY_GEAR' found within the 'trawl_buffs' featureclass table&lt;BR /&gt;gearVals = unique_values(trawlBuffs, "AGENCY_GEAR")&lt;BR /&gt;unique_gear = set(gearVals)&lt;/P&gt;&lt;P&gt;#loop through the years, create selection, union, make permanent&lt;BR /&gt;for year in unique_year:&lt;BR /&gt;yearSelectionClause = '{0} = {1}'.format('YEAR', year)&lt;BR /&gt;for gear in unique_gear:&lt;BR /&gt;gearSelectionClause = '{0} = "{1}"'.format('AGENCY_GEAR', gear)&lt;BR /&gt;new_layer = str([year, gear]) + "_union"&lt;BR /&gt;arcpy.MakeFeatureLayer_management(trawlBuffs, new_layer)&lt;BR /&gt;arcpy.SelectLayerByAttribute_management(new_layer, "NEW_SELECTION", newSelectionClause)&lt;BR /&gt;out_feat = unionOut + str(year)&lt;BR /&gt;arcpy.Union_analysis([fishnet, new_layer], out_feat)&lt;/P&gt;</description>
      <pubDate>Mon, 14 Mar 2022 23:55:25 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153608#M64053</guid>
      <dc:creator>ssintelmann</dc:creator>
      <dc:date>2022-03-14T23:55:25Z</dc:date>
    </item>
    <item>
      <title>Re: Arcpy Script to loop through field and run Union Analysis</title>
      <link>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153626#M64054</link>
      <description>&lt;P&gt;Revised double select above, this gets it closer, but fails at arcpy.SelectLayerByAttribute_management.&amp;nbsp;&lt;/P&gt;&lt;P&gt;#loop through the years/gears, create selection, union&lt;/P&gt;&lt;P&gt;for year in unique_year:&lt;BR /&gt;&amp;nbsp; &amp;nbsp; for gear in unique_gear:&lt;BR /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; new_layer = str(year) + str(gear) + "_union"&lt;BR /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; selectionClause = '{0} = {1}'.format('YEAR', year), '{0} = "{1}"'.format('AGENCY_GEAR', gear)&lt;BR /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; #selectionClause = '"YEAR" = ' + "'" + str(year) + "'", '"AGENCY_GEAR" = ' + "'" + gear + "'"&lt;BR /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; arcpy.MakeFeatureLayer_management(trawlBuffs, new_layer)&lt;BR /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; arcpy.SelectLayerByAttribute_management(new_layer, "NEW_SELECTION", selectionClause)&lt;BR /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; out_feat = unionOut + str(year) + str(gear)&lt;BR /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; arcpy.Union_analysis([fishnet, new_layer], out_feat)&lt;/P&gt;</description>
      <pubDate>Tue, 15 Mar 2022 00:43:18 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153626#M64054</guid>
      <dc:creator>ssintelmann</dc:creator>
      <dc:date>2022-03-15T00:43:18Z</dc:date>
    </item>
    <item>
      <title>Re: Arcpy Script to loop through field and run Union Analysis</title>
      <link>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153674#M64055</link>
      <description>&lt;P&gt;beat it up for hourS.&amp;nbsp; sql...ugh. this seemed to work.&amp;nbsp; thanks much for your help put in the right direction&lt;/P&gt;&lt;LI-CODE lang="python"&gt;try:
    for year in unique_year:
        for gear in unique_gear:
            selectionClause = '{0} = {1}'.format('YEAR', year) + str(" AND ") + '{0} = '"'{1}'"''.format('AGENCY_GEAR',gear)
            new_layer = str(year) + str(gear) 
            arcpy.MakeFeatureLayer_management(trawlBuffs, new_layer)
            arcpy.SelectLayerByAttribute_management(new_layer, "NEW_SELECTION", selectionClause)
            out_feat = unionOut + str(year) + str(gear)        
            arcpy.Union_analysis([fishnet, new_layer], out_feat)
            print("Writing Data File: " + out_feat)
except Exception as e:
    #dump errors
    print("Error: " + e.args[0]) 
finally:
    #Clean up the temp layer
    arcpy.Delete_management(new_layer)&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Tue, 15 Mar 2022 06:43:40 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/arcpy-script-to-loop-through-field-and-run-union/m-p/1153674#M64055</guid>
      <dc:creator>ssintelmann</dc:creator>
      <dc:date>2022-03-15T06:43:40Z</dc:date>
    </item>
  </channel>
</rss>

