Retrieve last Row and specific field values with SearchCursor












1















I have a shapefile from which I want to retrieve the last row values for specific fields to use them as input in a tool. So far this is what I have which does not work.



length=int(arcpy.GetCount_management(shapefile).getOutput(0))
print length
cursor=arcpy.SearchCursor(shapefile)
for row in cursor:
row= row[length-1]
endx= row.getValue("LastX")
endy= row.getValue("LastY")
sourcePoint= arcpy.Point(endx, endy)









share|improve this question



























    1















    I have a shapefile from which I want to retrieve the last row values for specific fields to use them as input in a tool. So far this is what I have which does not work.



    length=int(arcpy.GetCount_management(shapefile).getOutput(0))
    print length
    cursor=arcpy.SearchCursor(shapefile)
    for row in cursor:
    row= row[length-1]
    endx= row.getValue("LastX")
    endy= row.getValue("LastY")
    sourcePoint= arcpy.Point(endx, endy)









    share|improve this question

























      1












      1








      1








      I have a shapefile from which I want to retrieve the last row values for specific fields to use them as input in a tool. So far this is what I have which does not work.



      length=int(arcpy.GetCount_management(shapefile).getOutput(0))
      print length
      cursor=arcpy.SearchCursor(shapefile)
      for row in cursor:
      row= row[length-1]
      endx= row.getValue("LastX")
      endy= row.getValue("LastY")
      sourcePoint= arcpy.Point(endx, endy)









      share|improve this question














      I have a shapefile from which I want to retrieve the last row values for specific fields to use them as input in a tool. So far this is what I have which does not work.



      length=int(arcpy.GetCount_management(shapefile).getOutput(0))
      print length
      cursor=arcpy.SearchCursor(shapefile)
      for row in cursor:
      row= row[length-1]
      endx= row.getValue("LastX")
      endy= row.getValue("LastY")
      sourcePoint= arcpy.Point(endx, endy)






      arcpy cursor table






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 12 hours ago









      Krys01Krys01

      134




      134






















          4 Answers
          4






          active

          oldest

          votes


















          3














          Another variation, using list comprehension and da.SearchCursor:



          import arcpy
          shapefile = r'C:foldershapefile.shp'
          endx, endy = [i for i in arcpy.da.SearchCursor(shapefile,['LastX','LastY'])][-1] #-1 index for last record in list
          lastpoint = arcpy.Point(endx, endy)


          Im assuming LastX and LastY are fields. If you want the centroid's X and Y you can replace them with the SHAPE@X and SHAPE@Y tokens,






          share|improve this answer































            2














            A variation on getting the last row could also be this approach, it gets a count on the row and then queries for that specifically:



            objRes = arcpy.GetCount_management("myLayer")
            n = int(objRes.getOutput(0))
            sQuery = "OBJECTID >= " + str(n)
            with arcpy.da.SearchCursor("myLayer",["X","Y"],sQuery) as cursor:
            for row in cursor:
            x = row[0]
            y = row[1]
            print x,y





            share|improve this answer



















            • 1





              Perhaps change to FID = n-1, because he is dealing with shapefile.

              – FelixIP
              7 hours ago



















            1














            cursor = arcpy.SearchCursor(shapefile, None, None, None, "FID A")
            row = None
            for row in cursor:
            pass
            #row is now set as the last value returned by the iterator
            row.getValue("the field you want the value of")


            arcpy.SearchCursor returns an iterator, and to get the last item you need to iterate through all the items and keep a reference to the last one. Some more info here:
            https://stackoverflow.com/questions/2138873/cleanest-way-to-get-last-item-from-python-iterator



            Be careful what you mean by "last row". I'm not sure the SearchCursor is guaranteed to return rows in any specific order. When I tested on a shapfile the last item returned had FID == 0. Use the sort_fields argument to define the "last row" to be whatever you like based on the field(s) of your choice. (In this answer "FID A", with "A" meaning ascending sort order on the FID field.)
            http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-functions/searchcursor.htm



            Also, consider using the cursor from the Data Access module which offers improved performance.
            http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-data-access/searchcursor-class.htm






            share|improve this answer



















            • 4





              I definitely recommend using da.SearchCursor instead, as SearchCursor is deprecated.

              – smiller
              10 hours ago



















            1














            Dan has a good answer already posted but just to clarify why your code is failing: length is related to the number of rows, while row[length-1] is a specific column index (which probably doesn't exist since there's often more rows than columns. e.g. length = 53 (number of rows) would cause an error in general if there aren't 53 columns.



            An in-place fix for your code (not ideal as it involves unnecessary calculations for each row):



            length=int(arcpy.GetCount_management(shapefile).getOutput(0))
            print length
            cursor=arcpy.da.SearchCursor(shapefile) # switch to data access module
            for row in cursor:
            endx= row.getValue("LastX")
            endy= row.getValue("LastY")
            sourcePoint= arcpy.Point(endx, endy)


            sourcePoint only uses the final endx and endy values returned by cursor, since this is now outside of the loop.






            share|improve this answer























              Your Answer








              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "79"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f312248%2fretrieve-last-row-and-specific-field-values-with-searchcursor%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              3














              Another variation, using list comprehension and da.SearchCursor:



              import arcpy
              shapefile = r'C:foldershapefile.shp'
              endx, endy = [i for i in arcpy.da.SearchCursor(shapefile,['LastX','LastY'])][-1] #-1 index for last record in list
              lastpoint = arcpy.Point(endx, endy)


              Im assuming LastX and LastY are fields. If you want the centroid's X and Y you can replace them with the SHAPE@X and SHAPE@Y tokens,






              share|improve this answer




























                3














                Another variation, using list comprehension and da.SearchCursor:



                import arcpy
                shapefile = r'C:foldershapefile.shp'
                endx, endy = [i for i in arcpy.da.SearchCursor(shapefile,['LastX','LastY'])][-1] #-1 index for last record in list
                lastpoint = arcpy.Point(endx, endy)


                Im assuming LastX and LastY are fields. If you want the centroid's X and Y you can replace them with the SHAPE@X and SHAPE@Y tokens,






                share|improve this answer


























                  3












                  3








                  3







                  Another variation, using list comprehension and da.SearchCursor:



                  import arcpy
                  shapefile = r'C:foldershapefile.shp'
                  endx, endy = [i for i in arcpy.da.SearchCursor(shapefile,['LastX','LastY'])][-1] #-1 index for last record in list
                  lastpoint = arcpy.Point(endx, endy)


                  Im assuming LastX and LastY are fields. If you want the centroid's X and Y you can replace them with the SHAPE@X and SHAPE@Y tokens,






                  share|improve this answer













                  Another variation, using list comprehension and da.SearchCursor:



                  import arcpy
                  shapefile = r'C:foldershapefile.shp'
                  endx, endy = [i for i in arcpy.da.SearchCursor(shapefile,['LastX','LastY'])][-1] #-1 index for last record in list
                  lastpoint = arcpy.Point(endx, endy)


                  Im assuming LastX and LastY are fields. If you want the centroid's X and Y you can replace them with the SHAPE@X and SHAPE@Y tokens,







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 10 hours ago









                  BERABERA

                  15.9k52042




                  15.9k52042

























                      2














                      A variation on getting the last row could also be this approach, it gets a count on the row and then queries for that specifically:



                      objRes = arcpy.GetCount_management("myLayer")
                      n = int(objRes.getOutput(0))
                      sQuery = "OBJECTID >= " + str(n)
                      with arcpy.da.SearchCursor("myLayer",["X","Y"],sQuery) as cursor:
                      for row in cursor:
                      x = row[0]
                      y = row[1]
                      print x,y





                      share|improve this answer



















                      • 1





                        Perhaps change to FID = n-1, because he is dealing with shapefile.

                        – FelixIP
                        7 hours ago
















                      2














                      A variation on getting the last row could also be this approach, it gets a count on the row and then queries for that specifically:



                      objRes = arcpy.GetCount_management("myLayer")
                      n = int(objRes.getOutput(0))
                      sQuery = "OBJECTID >= " + str(n)
                      with arcpy.da.SearchCursor("myLayer",["X","Y"],sQuery) as cursor:
                      for row in cursor:
                      x = row[0]
                      y = row[1]
                      print x,y





                      share|improve this answer



















                      • 1





                        Perhaps change to FID = n-1, because he is dealing with shapefile.

                        – FelixIP
                        7 hours ago














                      2












                      2








                      2







                      A variation on getting the last row could also be this approach, it gets a count on the row and then queries for that specifically:



                      objRes = arcpy.GetCount_management("myLayer")
                      n = int(objRes.getOutput(0))
                      sQuery = "OBJECTID >= " + str(n)
                      with arcpy.da.SearchCursor("myLayer",["X","Y"],sQuery) as cursor:
                      for row in cursor:
                      x = row[0]
                      y = row[1]
                      print x,y





                      share|improve this answer













                      A variation on getting the last row could also be this approach, it gets a count on the row and then queries for that specifically:



                      objRes = arcpy.GetCount_management("myLayer")
                      n = int(objRes.getOutput(0))
                      sQuery = "OBJECTID >= " + str(n)
                      with arcpy.da.SearchCursor("myLayer",["X","Y"],sQuery) as cursor:
                      for row in cursor:
                      x = row[0]
                      y = row[1]
                      print x,y






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 8 hours ago









                      HornbyddHornbydd

                      26.4k32757




                      26.4k32757








                      • 1





                        Perhaps change to FID = n-1, because he is dealing with shapefile.

                        – FelixIP
                        7 hours ago














                      • 1





                        Perhaps change to FID = n-1, because he is dealing with shapefile.

                        – FelixIP
                        7 hours ago








                      1




                      1





                      Perhaps change to FID = n-1, because he is dealing with shapefile.

                      – FelixIP
                      7 hours ago





                      Perhaps change to FID = n-1, because he is dealing with shapefile.

                      – FelixIP
                      7 hours ago











                      1














                      cursor = arcpy.SearchCursor(shapefile, None, None, None, "FID A")
                      row = None
                      for row in cursor:
                      pass
                      #row is now set as the last value returned by the iterator
                      row.getValue("the field you want the value of")


                      arcpy.SearchCursor returns an iterator, and to get the last item you need to iterate through all the items and keep a reference to the last one. Some more info here:
                      https://stackoverflow.com/questions/2138873/cleanest-way-to-get-last-item-from-python-iterator



                      Be careful what you mean by "last row". I'm not sure the SearchCursor is guaranteed to return rows in any specific order. When I tested on a shapfile the last item returned had FID == 0. Use the sort_fields argument to define the "last row" to be whatever you like based on the field(s) of your choice. (In this answer "FID A", with "A" meaning ascending sort order on the FID field.)
                      http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-functions/searchcursor.htm



                      Also, consider using the cursor from the Data Access module which offers improved performance.
                      http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-data-access/searchcursor-class.htm






                      share|improve this answer



















                      • 4





                        I definitely recommend using da.SearchCursor instead, as SearchCursor is deprecated.

                        – smiller
                        10 hours ago
















                      1














                      cursor = arcpy.SearchCursor(shapefile, None, None, None, "FID A")
                      row = None
                      for row in cursor:
                      pass
                      #row is now set as the last value returned by the iterator
                      row.getValue("the field you want the value of")


                      arcpy.SearchCursor returns an iterator, and to get the last item you need to iterate through all the items and keep a reference to the last one. Some more info here:
                      https://stackoverflow.com/questions/2138873/cleanest-way-to-get-last-item-from-python-iterator



                      Be careful what you mean by "last row". I'm not sure the SearchCursor is guaranteed to return rows in any specific order. When I tested on a shapfile the last item returned had FID == 0. Use the sort_fields argument to define the "last row" to be whatever you like based on the field(s) of your choice. (In this answer "FID A", with "A" meaning ascending sort order on the FID field.)
                      http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-functions/searchcursor.htm



                      Also, consider using the cursor from the Data Access module which offers improved performance.
                      http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-data-access/searchcursor-class.htm






                      share|improve this answer



















                      • 4





                        I definitely recommend using da.SearchCursor instead, as SearchCursor is deprecated.

                        – smiller
                        10 hours ago














                      1












                      1








                      1







                      cursor = arcpy.SearchCursor(shapefile, None, None, None, "FID A")
                      row = None
                      for row in cursor:
                      pass
                      #row is now set as the last value returned by the iterator
                      row.getValue("the field you want the value of")


                      arcpy.SearchCursor returns an iterator, and to get the last item you need to iterate through all the items and keep a reference to the last one. Some more info here:
                      https://stackoverflow.com/questions/2138873/cleanest-way-to-get-last-item-from-python-iterator



                      Be careful what you mean by "last row". I'm not sure the SearchCursor is guaranteed to return rows in any specific order. When I tested on a shapfile the last item returned had FID == 0. Use the sort_fields argument to define the "last row" to be whatever you like based on the field(s) of your choice. (In this answer "FID A", with "A" meaning ascending sort order on the FID field.)
                      http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-functions/searchcursor.htm



                      Also, consider using the cursor from the Data Access module which offers improved performance.
                      http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-data-access/searchcursor-class.htm






                      share|improve this answer













                      cursor = arcpy.SearchCursor(shapefile, None, None, None, "FID A")
                      row = None
                      for row in cursor:
                      pass
                      #row is now set as the last value returned by the iterator
                      row.getValue("the field you want the value of")


                      arcpy.SearchCursor returns an iterator, and to get the last item you need to iterate through all the items and keep a reference to the last one. Some more info here:
                      https://stackoverflow.com/questions/2138873/cleanest-way-to-get-last-item-from-python-iterator



                      Be careful what you mean by "last row". I'm not sure the SearchCursor is guaranteed to return rows in any specific order. When I tested on a shapfile the last item returned had FID == 0. Use the sort_fields argument to define the "last row" to be whatever you like based on the field(s) of your choice. (In this answer "FID A", with "A" meaning ascending sort order on the FID field.)
                      http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-functions/searchcursor.htm



                      Also, consider using the cursor from the Data Access module which offers improved performance.
                      http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-data-access/searchcursor-class.htm







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 10 hours ago









                      Dan JurgellaDan Jurgella

                      2,163613




                      2,163613








                      • 4





                        I definitely recommend using da.SearchCursor instead, as SearchCursor is deprecated.

                        – smiller
                        10 hours ago














                      • 4





                        I definitely recommend using da.SearchCursor instead, as SearchCursor is deprecated.

                        – smiller
                        10 hours ago








                      4




                      4





                      I definitely recommend using da.SearchCursor instead, as SearchCursor is deprecated.

                      – smiller
                      10 hours ago





                      I definitely recommend using da.SearchCursor instead, as SearchCursor is deprecated.

                      – smiller
                      10 hours ago











                      1














                      Dan has a good answer already posted but just to clarify why your code is failing: length is related to the number of rows, while row[length-1] is a specific column index (which probably doesn't exist since there's often more rows than columns. e.g. length = 53 (number of rows) would cause an error in general if there aren't 53 columns.



                      An in-place fix for your code (not ideal as it involves unnecessary calculations for each row):



                      length=int(arcpy.GetCount_management(shapefile).getOutput(0))
                      print length
                      cursor=arcpy.da.SearchCursor(shapefile) # switch to data access module
                      for row in cursor:
                      endx= row.getValue("LastX")
                      endy= row.getValue("LastY")
                      sourcePoint= arcpy.Point(endx, endy)


                      sourcePoint only uses the final endx and endy values returned by cursor, since this is now outside of the loop.






                      share|improve this answer




























                        1














                        Dan has a good answer already posted but just to clarify why your code is failing: length is related to the number of rows, while row[length-1] is a specific column index (which probably doesn't exist since there's often more rows than columns. e.g. length = 53 (number of rows) would cause an error in general if there aren't 53 columns.



                        An in-place fix for your code (not ideal as it involves unnecessary calculations for each row):



                        length=int(arcpy.GetCount_management(shapefile).getOutput(0))
                        print length
                        cursor=arcpy.da.SearchCursor(shapefile) # switch to data access module
                        for row in cursor:
                        endx= row.getValue("LastX")
                        endy= row.getValue("LastY")
                        sourcePoint= arcpy.Point(endx, endy)


                        sourcePoint only uses the final endx and endy values returned by cursor, since this is now outside of the loop.






                        share|improve this answer


























                          1












                          1








                          1







                          Dan has a good answer already posted but just to clarify why your code is failing: length is related to the number of rows, while row[length-1] is a specific column index (which probably doesn't exist since there's often more rows than columns. e.g. length = 53 (number of rows) would cause an error in general if there aren't 53 columns.



                          An in-place fix for your code (not ideal as it involves unnecessary calculations for each row):



                          length=int(arcpy.GetCount_management(shapefile).getOutput(0))
                          print length
                          cursor=arcpy.da.SearchCursor(shapefile) # switch to data access module
                          for row in cursor:
                          endx= row.getValue("LastX")
                          endy= row.getValue("LastY")
                          sourcePoint= arcpy.Point(endx, endy)


                          sourcePoint only uses the final endx and endy values returned by cursor, since this is now outside of the loop.






                          share|improve this answer













                          Dan has a good answer already posted but just to clarify why your code is failing: length is related to the number of rows, while row[length-1] is a specific column index (which probably doesn't exist since there's often more rows than columns. e.g. length = 53 (number of rows) would cause an error in general if there aren't 53 columns.



                          An in-place fix for your code (not ideal as it involves unnecessary calculations for each row):



                          length=int(arcpy.GetCount_management(shapefile).getOutput(0))
                          print length
                          cursor=arcpy.da.SearchCursor(shapefile) # switch to data access module
                          for row in cursor:
                          endx= row.getValue("LastX")
                          endy= row.getValue("LastY")
                          sourcePoint= arcpy.Point(endx, endy)


                          sourcePoint only uses the final endx and endy values returned by cursor, since this is now outside of the loop.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 10 hours ago









                          smillersmiller

                          1,984217




                          1,984217






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f312248%2fretrieve-last-row-and-specific-field-values-with-searchcursor%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                              Alcedinidae

                              RAC Tourist Trophy