Cesar
Cesar

Reputation: 585

Converting Weekly timeseries into Daily (with a proportion criteria)

I have a Dataframe representing Daily product demand. Because this product`s demand is irregular, the prophet model doesn't perform very well, as it shows below:

Daily

Therefore, I converted into weekly timeseries, and the model fitted better.

df.resample('W',how={'y': 'sum'}, 
                loffset=pd.offsets.timedelta(days=-6))

Weekly Model

What I am trying to do now:

1 - Converting into daily again, respecting this weekly seasonality:

Seasonality

Weekday Priority:

  1. Saturday
  2. Tuesday
  3. Friday
  4. Monday
  5. Thursday
  6. Wednesday
  7. Sunday

So, if my prediction for the first week is a demand equals 3, I want that occurs this:

  1. Saturday : 1
  2. Tuesday : 1
  3. Friday : 1
  4. Monday : 0
  5. Thursday : 0
  6. Wednesday : 0
  7. Sunday : 0

I mean, transferring every weekly prediction into daily respecting this week order to assign values:

         ds      y
0   2018-01-07  5.0
1   2018-01-14  5.0
2   2018-01-21  4.0

Expected result:

         ds      y
0   2018-01-01  1
1   2018-01-02  1
2   2018-01-03  0 (Wednesday)
3   2018-01-04  1
4   2018-01-05  1
5   2018-01-06  1
6   2018-01-07  0 (Sunday)

Upvotes: 3

Views: 302

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150745

Since you data is date-indexed, I bet it's not that very long. So we can construct a function, and apply:

def to_daily(val):
    # order of the day in a week
    order = np.argsort([5, 1, 4, 0, 3, 2, 6])

    b, r = val//7, val%7
    ret = np.array([b+1]*r + [b]*(7-r))

    return ret[order]

to_daily(5)
# array([1, 1, 0, 1, 1, 1, 0])

ret_df  = pd.DataFrame({'ds': pd.date_range(df.ds[0]-pd.to_timedelta('6d'),
                                 df.ds.values[-1], freq='d'),
                           'y' : np.array([to_daily(val) 
                                 for val in df.y.astype(int)]).flatten()})
ret_df

Output:

    ds                     y
--  -------------------  ---
 0  2018-01-01 00:00:00    1
 1  2018-01-02 00:00:00    1
 2  2018-01-03 00:00:00    0
 3  2018-01-04 00:00:00    1
 4  2018-01-05 00:00:00    1
 5  2018-01-06 00:00:00    1
 6  2018-01-07 00:00:00    0
 7  2018-01-08 00:00:00    1
 8  2018-01-09 00:00:00    1
 9  2018-01-10 00:00:00    0
10  2018-01-11 00:00:00    0
11  2018-01-12 00:00:00    1
12  2018-01-13 00:00:00    1
13  2018-01-14 00:00:00    0
14  2018-01-15 00:00:00    1
15  2018-01-16 00:00:00    1
16  2018-01-17 00:00:00    1
17  2018-01-18 00:00:00    1
18  2018-01-19 00:00:00    1
19  2018-01-20 00:00:00    2
20  2018-01-21 00:00:00    1

Upvotes: 2

Related Questions