简体   繁体   中英

How to use Lag value of a column in condition to populate another column in Pandas

I have a table like below:

在此处输入图像描述

I want to create another column(Check2) with below logic:

  • If Check1 ==0 then Check2 = A
  • Else Check2 = Check2(lagged value) - B(lagged) - C(lagged)

Expected Output should be like below -

在此处输入图像描述

I have written below code but its taking very long time(in hours) for 50000 records, please help

for i in range(len(df)): 
            if df.loc[i,'Check1'] == 0:
                df.loc[i,'Check2'] = df.loc[i,'Volume']
            else:
                df.loc[i,'Check2'] = df.loc[i-1,'Check2'] - df.loc[i-1,'B'] -df.loc[i-1,'C']

You are searching for: .shift() function. It does what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM