Dec-08-2022, 05:17 AM
Hi,
Basically, I want to impute 1 in 'Check' column if the previous row of 'days' is >=0 and <7.
I wrote the below code, but it only looks at current row of 'days' column.
Thank you
Weekly MonthEnd days check
Period
1989-01-20 3 1989-01-31 11 NaN
1989-01-27 4 1989-01-31 4 1.0
1989-02-03 2 1989-02-28 25 NaN
1989-02-10 5 1989-02-28 18 NaN
1989-02-17 3 1989-02-28 11 NaN
1989-02-24 5 1989-02-28 4 1.0
1989-03-03 5 1989-03-31 28 NaN
Desired Output
Weekly MonthEnd days check
Period
1989-01-20 3 1989-01-31 11 NaN
1989-01-27 4 1989-01-31 4 NaN
1989-02-03 2 1989-02-28 25 1.0
1989-02-10 5 1989-02-28 18 NaN
1989-02-17 3 1989-02-28 11 NaN
1989-02-24 5 1989-02-28 4 NaN
1989-03-03 5 1989-03-31 28 1.0
Basically, I want to impute 1 in 'Check' column if the previous row of 'days' is >=0 and <7.
I wrote the below code, but it only looks at current row of 'days' column.
Thank you
def impute(df): if df['days']>=0 and df['days']<7: return 1 df['check']=df.apply(impute, axis=1)Current output
Weekly MonthEnd days check
Period
1989-01-20 3 1989-01-31 11 NaN
1989-01-27 4 1989-01-31 4 1.0
1989-02-03 2 1989-02-28 25 NaN
1989-02-10 5 1989-02-28 18 NaN
1989-02-17 3 1989-02-28 11 NaN
1989-02-24 5 1989-02-28 4 1.0
1989-03-03 5 1989-03-31 28 NaN
Desired Output
Weekly MonthEnd days check
Period
1989-01-20 3 1989-01-31 11 NaN
1989-01-27 4 1989-01-31 4 NaN
1989-02-03 2 1989-02-28 25 1.0
1989-02-10 5 1989-02-28 18 NaN
1989-02-17 3 1989-02-28 11 NaN
1989-02-24 5 1989-02-28 4 NaN
1989-03-03 5 1989-03-31 28 1.0