Python Forum
Impute 1 if previous row of 'days' column is between 0 & 7
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Impute 1 if previous row of 'days' column is between 0 & 7
#1
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
Reply
#2
input df please
Reply
#3
You can shift the days column.
import pandas as pd
df = pd.DataFrame({"Count":range(5)})
df[Shifted'] = df['Count'].shift(1)
print(df)
Output:
Count Shifted 0 0 NaN 1 1 0.0 2 2 1.0 3 3 2.0 4 4 3.0
Then you could use the shifted column in your function
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How replace Unnamed header column with previous SriMekala 3 5,197 Aug-15-2019, 05:10 PM
Last Post: boring_accountant

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020