0

I have this script that creates a feature class for every month from 2014-2017. However, I would now like to have the monthly data add on to each other. For example, instead of it going [Jan, Feb, Mar] I would want it to go [Jan, Jan+Feb, Jan+Feb+Mar]. However, I do not know how to do this in ArcPy and I can't find any examples online anywhere.

Here is my code:

import arcpy
import datetime 
from datetime import timedelta
import time
import calendar

# Set environment settings
arcpy.env.workspace = r"C:\arcGIS_Shared\Python\CenterHeatMaps5.gdb"

#Declare variables
fc = 'Open_GoHealth_Centers'
fields = ['USER_market_id','USER_GoHealth_ID','USER_GoHealth_Center_Name','USER_Opening_Date']
fieldname = 'USER_market_id'

# Set Markets to loop through
markets = [1000,2000,3000,4000]
# Set Years to loop through
years = [2014,2015,2016,2017]
# Set Months to loop through
months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

sqlclause = (None, 'Order By USER_market_id, USER_GoHealth_ID')

#returns last day of each month
def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
    return next_month - datetime.timedelta(days=next_month.day)

for market in markets:
    print (market)

    #Define WHERE clause statement
    whereclause = """{} = """.format(arcpy.AddFieldDelimiters(fc, fieldname)) + str(market)

    for year in years:
        print (year)
        for month in months:
            print (month)
            with arcpy.da.SearchCursor(in_table = fc, field_names = fields, where_clause=whereclause, sql_clause=(None, 'ORDER BY USER_market_id, USER_GoHealth_ID')) as cursor:
                #Loop through each row established in cursor
                for row in (cursor):
                    # Set local variables for the FeatureClasstoFeatureClass tool
                    inFeatures = "PatientVisitsGeocoded"
                    outLocation = r"C:\arcGIS_Shared\Python\CenterHeatMaps5.gdb"
                    outFeatureClass = "PatientVisits{0}_{1}_{3}_{2}".format(row[0], row[2], month, year)
                    delimitedfield = arcpy.AddFieldDelimiters(arcpy.env.workspace,"USER_CenterID")
                    expression = """{0} = {1} AND USER_DOSMonth = '{2}' AND USER_DOSYear = {3}""".format(delimitedfield, row[1], calendar.month_abbr[month], year)


    #               Execute FeatureClassToFeatureClass tool
    #               This If statement determines if the Opening_Date of the respective center is before the last day of the month being run.
    #               If it is, the feature class is copied, if not, the feature class is skipped.
                    if last_day_of_month(datetime.date(year, month, 1)) >= row[3].date():
                        arcpy.FeatureClassToFeatureClass_conversion(inFeatures, outLocation, outFeatureClass, expression)

                        #Print Results
                        print(row[2])

Update----------- I have tried using NumPy and cumsum, but I know get the following error

if last_day_of_month(datetime.date(year, np.cumsum(months), 1)) >= row[3].date():

TypeError: only length-1 arrays can be converted to Python scalars

At first I thought this was because I was using a list for months instead of an array, but then I converted the list to an array (or at least I think I did) and I still get the same error.

Do you think this method will work?

Here is my new code:

 import arcpy
    import datetime 
    import time
    import calendar
    import numpy as np
    from numpy import array
    from datetime import timedelta

    # Set environment settings
    arcpy.env.workspace = r"C:\arcGIS_Shared\Python\CenterHeatMaps6.gdb"

    #Declare variables
    fc = 'Open_GoHealth_Centers'
    fields = ['USER_market_id','USER_GoHealth_ID','USER_GoHealth_Center_Name','USER_Opening_Date']
    fieldname = 'USER_market_id'

    # Set Markets to loop through
    markets = [4000]
    # Set Years to loop through
    years = [2017]
    # Set Months to loop through
    months = array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

    #Cumulative Sum of Months
    np.cumsum(months)

    sqlclause = (None, 'Order By USER_market_id, USER_GoHealth_ID')

    #returns last day of each month
    def last_day_of_month(any_day):
        next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
        return next_month - datetime.timedelta(days=next_month.day)

    for market in markets:


        #Define WHERE clause statement
        whereclause = """{} = """.format(arcpy.AddFieldDelimiters(fc, fieldname)) + str(market)

        for year in years:

            for month in np.cumsum(months):
                with arcpy.da.SearchCursor(in_table = fc, field_names = fields, where_clause=whereclause, sql_clause=(None, 'ORDER BY USER_market_id, USER_GoHealth_ID')) as cursor:
                    #Loop through each row established in cursor
                    for row in (cursor):
                        # Set local variables for the FeatureClasstoFeatureClass tool
                        inFeatures = "PatientVisitsGeocoded"
                        outLocation = r"C:\arcGIS_Shared\Python\CenterHeatMaps6.gdb"
                        outFeatureClass = "PatientVisits{0}_{1}_{3}_{2}".format(row[0], row[2], np.cumsum(months), year)
                        delimitedfield = arcpy.AddFieldDelimiters(arcpy.env.workspace,"USER_CenterID")
                        expression = """{0} = {1} AND USER_DOSMonth = '{2}' AND USER_DOSYear = {3}""".format(delimitedfield, row[1], np.cumsum(month), year) #calendar.month_abbr[month]


        #               Execute FeatureClassToFeatureClass tool
        #               This If statement determines if the Opening_Date of the respective center is before the last day of the month being run.
        #               If it is, the feature class is copied, if not, the feature class is skipped.
                        if last_day_of_month(datetime.date(year, np.cumsum(months), 1)) >= row[3].date():
                            arcpy.FeatureClassToFeatureClass_conversion(inFeatures, outLocation, outFeatureClass, expression)
1

In order to select out additional details each pass through your loop, you will need to update your WHERE clause. Perhaps create a list of the desired WHERE clauses based on your year and month list? Or put your WHERE clause into the loop and modify it there.

  • Could you give me an example of a "list of desired WHERE clauses"? I'm not exactly sure what that would look like – Matt A. Feb 12 '18 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.