Сhange start day of the week for LabelMaker (composeml libraries)

Viewed 129

I am trying to create labels for a customer and a week period. I need labeling_function to calculate the sale amount from Monday inclusive to Monday not inclusive. But now it's calculating from Sunday to Sunday. How to change start day of the week for LabelMaker

def total_spent(df):
    total = df['amount'].sum()
    return total

label_maker = cp.LabelMaker(
    target_entity="customer_id",
    time_index="transaction_time",
    labeling_function=total_spent,
    window_size="W",
)
1 Answers

Thanks for the question. You can get the weekly frequency on Mondays by setting the window size to W-MON. I'll go through a quick example with this data.

import pandas as pd

records = []
for time in  pd.date_range(start='2020-11-16', periods=15, freq='d'):
    record = {'transaction_time': time, 'day_name': time.day_name()}
    records.append(record)

df = pd.DataFrame(records).assign(customer_id=0)
transaction_time   day_name  customer_id
      2020-11-16     Monday            0
      2020-11-17    Tuesday            0
      2020-11-18  Wednesday            0
      2020-11-19   Thursday            0
      2020-11-20     Friday            0
      2020-11-21   Saturday            0
      2020-11-22     Sunday            0
      2020-11-23     Monday            0
      2020-11-24    Tuesday            0
      2020-11-25  Wednesday            0
      2020-11-26   Thursday            0
      2020-11-27     Friday            0
      2020-11-28   Saturday            0
      2020-11-29     Sunday            0
      2020-11-30     Monday            0

In the label maker, I set the window size to W-MON. This is an offset alias for a weekly frequency on Mondays. The window size also supports many other offset aliases from pandas.

import composeml as cp

lm = cp.LabelMaker(
    target_entity='customer_id',
    time_index='transaction_time',
    window_size='W-MON',
)

Let's inspect the data slices generated by the label maker. You should get a weekly frequency on Mondays.

slices = lm.slice(df, -1)
next(slices)
                   day_name  customer_id
transaction_time                        
2020-11-16           Monday            0
2020-11-17          Tuesday            0
2020-11-18        Wednesday            0
2020-11-19         Thursday            0
2020-11-20           Friday            0
2020-11-21         Saturday            0
2020-11-22           Sunday            0
next(slices)
                   day_name  customer_id
transaction_time                        
2020-11-23           Monday            0
2020-11-24          Tuesday            0
2020-11-25        Wednesday            0
2020-11-26         Thursday            0
2020-11-27           Friday            0
2020-11-28         Saturday            0
2020-11-29           Sunday            0
Related