简体   繁体   English

如何在条件中使用列的滞后值填充 Pandas 中的另一列

[英]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:我想用以下逻辑创建另一列(Check2):

  • If Check1 ==0 then Check2 = A如果 Check1 ==0 则 Check2 = A
  • Else Check2 = Check2(lagged value) - B(lagged) - C(lagged)否则 Check2 = Check2(滞后值) - B(滞后) - C(滞后)

Expected Output should be like below -预期的 Output 应该如下所示 -

在此处输入图像描述

I have written below code but its taking very long time(in hours) for 50000 records, please help我已经写了下面的代码,但是对于 50000 条记录需要很长时间(以小时为单位),请帮助

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.您正在搜索: .shift() function。 It does what you want它做你想做的事

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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