如何使用python apply / lambda / shift函数基于2列的值获取该特定列的前一行值? [英] How to use python apply/lambda/shift function to get the previous row value of that particular column based on the value of 2 columns?

查看:65
本文介绍了如何使用python apply / lambda / shift函数基于2列的值获取该特定列的前一行值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2列(FN1和FN2),因此我必须再创建一列(最终)

I have 2 columns(FN1 and FN2) and based on these i have to create one more column(Final)

FN1     FN2    Final
False   False   1
True    True    1
False   False   1
True    False   2
True    True    2
False   False   1 
True    True    1
True    True    1




  • 如果FN1如果为False,则Final将为1。

    • If FN1 is False, Final will be 1.

      如果FN2为True,则我将是Final的先前值。

      If FN2 is True i will be the previous value of Final.

      但是,如果FN2为False,我需要用
      的前一个值(最后加1)更新它(即递增1)

      But if FN2 is False i need to update it with the previous value of Final +1 (i.e. increment by 1)

      。我尝试使用 shift()来做到这一点,但在这种情况下又无济于事。

      . I tried doing it using shift() but again that does not help in this scenario.

      FN1     FN2    Final
      False   False   1
      True    True    1
      False   False   1
      True    False   2
      True    True    2
      False   False   1 
      True    True    1
      True    True    1
      

      推荐答案

      使用 np.select

      df1 = df.shift()
      
      cond1 = df['FN1'] == False
      cond2 = (df['FN1']==True) & (df['FN2'] ==True)
      cond3 = (df['FN1']==True) & (df['FN2'] == False)
      
      df['Final'] = np.select([cond1,cond2,cond3], [1, df1['Final'], df1['Final']+1])
      
      print(df)
      

      这篇关于如何使用python apply / lambda / shift函数基于2列的值获取该特定列的前一行值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆