Impute 1 if previous row of 'days' column is between 0 & 7 - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Impute 1 if previous row of 'days' column is between 0 & 7 (/thread-38900.html) |
Impute 1 if previous row of 'days' column is between 0 & 7 - JaneTan - Dec-08-2022 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 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 RE: Impute 1 if previous row of 'days' column is between 0 & 7 - Larz60+ - Dec-08-2022 input df please RE: Impute 1 if previous row of 'days' column is between 0 & 7 - deanhystad - Dec-08-2022 You can shift the days column. import pandas as pd df = pd.DataFrame({"Count":range(5)}) df[Shifted'] = df['Count'].shift(1) print(df) Then you could use the shifted column in your function
|