How to fill by counting last and forward N values with static window in pandas

Viewed 55

I have a calendar data of type of dayworks - the day is the holiday or not. I want to create a new feautures:

  1. The value in the cell is the number of holidays in the week.
  2. The value in the cell is the number of holidays in the N-window (right and left windows). In example - N=5 (and including current value)

Example:

         is_holiday   feature_1 feature_2
idx                                 
0          0              2         0     
1          0              2         1
2          0              2         2
3          0              2         2
4          0              2         2
5          1              2         2
6          1              2         2
7          0              3         3
8          0              3         4
9          0              3         5
10         0              3         4
11         1              3         3  
12         1              3         3
13         1              3         3
...
1 Answers

I think you need grouping for each 7 values and aggregate sum and for second is used Series.rolling:

df['f1'] = df.groupby(df.index // 7)['is_holiday'].transform('sum')
df['f2'] = df['is_holiday'].rolling(9, center=True, min_periods=1).sum().astype(int)
print (df)
     is_holiday  feature_1  feature_2  f1  f2
idx                                          
0             0          2          0   2   0
1             0          2          1   2   1
2             0          2          2   2   2
3             0          2          2   2   2
4             0          2          2   2   2
5             1          2          2   2   2
6             1          2          2   2   2
7             0          3          3   3   3
8             0          3          4   3   4
9             0          3          5   3   5
10            0          3          4   3   4
11            1          3          3   3   3
12            1          3          3   3   3
13            1          3          3   3   3
Related