Is it possible to dynamically assign condition statements to a list in Python?

Viewed 21

I am trying to create a list of conditions to use the numpy select statement to create a 'Week #' column depending on the date a record was created. However, it doesn't quite seem to work. Any suggestions?

#Creating list for start dates
weekStartDay = []
weekValues = []
weekConditions = []
counter = 1

demoStartDate = min(demographic['Date'])
demoEndDate = max(demographic['Date'])

while demoStartDate <= demoEndDate:
    weekStartDay.append(demoStartDate)
    demoStartDate += timedelta(days=7)

weekStartDay.append(demoStartDate)

while counter <= len(weekConditions):
    weekValues.append(counter+1)
    counter += 1

#Assigning condition statement for numpy conditions
for i in range(len(weekStartDay)):
       weekConditions.append( (demographic['Date'] >= weekStartDay[i]) & (demographic['Date'] < weekStartDay[i+1]) )

#Creating week value assignment column
demographic['Week'] = np.select(weekConditions,weekValues)
1 Answers

I believe I've found a solution to the problem.

#Creating list for start dates
weekStartDay = []
weekValues = []
weekConditions = []
counter = 1
i = 0

demoStartDate = min(demographic['Date'])
demoEndDate = max(demographic['Date'])

while demoStartDate <= demoEndDate:
    weekStartDay.append(demoStartDate)
    demoStartDate += timedelta(days=7)

weekStartDay.append(demoStartDate)

while counter <= len(weekStartDay):
    weekValues.append(counter)
    counter += 1

#Assigning condition statement for numpy conditions
while i != len(weekStartDay):   
    for i in range(len(weekStartDay)):
        weekConditions.append( (demographic['Date'] >= weekStartDay[i-1]) & (demographic['Date'] < weekStartDay[i]) )
        i += 1

#Creating week value assignment column
demographic['Week'] = np.select(weekConditions,weekValues)
Related