pandas dataframe new column which checks previous day

I have a Dataframe which has a Datetime as Index and a column named "Holiday" which is an Flag with 1 or 0.

So if the datetimeindex is a holiday, the Holiday column has 1 in it and if not so 0.

I need a new column that says whether a given datetimeindex is the first day after a holiday or not.The new column should just look if its previous day has the flag "HOLIDAY" set to 1 and then set its flag to 1, otherwise 0.

EDIT

Doing:

df['DayAfter'] = df.Holiday.shift(1).fillna(0)

Has the Output:

                        Holiday    DayAfter     AnyNumber  
Datum                                                
...
2014-01-01 20:00:00         1        1.0          9  
2014-01-01 20:30:00         1        1.0          2  
2014-01-01 21:00:00         1        1.0          3  
2014-01-01 21:30:00         1        1.0          3  
2014-01-01 22:00:00         1        1.0          6  
2014-01-01 22:30:00         1        1.0          1  
2014-01-01 23:00:00         1        1.0          1  
2014-01-01 23:30:00         1        1.0          1  
2014-01-02 00:00:00         0        1.0          1  
2014-01-02 00:30:00         0        0.0          2  
2014-01-02 01:00:00         0        0.0          1  
2014-01-02 01:30:00         0        0.0          1 
...

if you check the first timestamp for 2014-01-02 the DayAfter flag is set right. But the other flags are 0. Thats wrong.

1 answer

  • answered 2018-04-14 17:46 DJK

    Create an array of unique days that are holidays and offset them by one day

    days = pd.Series(df[df.Holiday == 1].index).add(pd.DateOffset(1)).dt.date.unique()
    

    Create a new column with the one day holiday offsets (days)

    df['DayAfter'] = np.where(pd.Series(df.index).dt.date.isin(days),1,0)
    
    
    
                     Holiday  AnyNumber  DayAfter
    Datum
    2014-01-01 20:00:00        1          9         0
    2014-01-01 20:30:00        1          2         0
    2014-01-01 21:00:00        1          3         0
    2014-01-01 21:30:00        1          3         0
    2014-01-01 22:00:00        1          6         0
    2014-01-01 22:30:00        1          1         0
    2014-01-01 23:00:00        1          1         0
    2014-01-01 23:30:00        1          1         0
    2014-01-02 00:00:00        0          1         1
    2014-01-02 00:30:00        0          2         1
    2014-01-02 01:00:00        0          1         1
    2014-01-02 01:30:00        0          1         1