Reference previous row when iterating through dataframe

后端 未结 3 869
夕颜
夕颜 2021-01-25 11:13

Is there a simple way to reference the previous row when iterating through a dataframe? In the following dataframe I would like column B to change to 1 when A > 1

3条回答
  •  执笔经年
    2021-01-25 11:40

    This is what you are trying to do?

    In [38]: df = DataFrame(randn(10,2),columns=list('AB'))
    
    In [39]: df['B'] = np.nan
    
    In [40]: df.loc[df.A<-1,'B'] = -1
    
    In [41]: df.loc[df.A>1,'B'] = 1
    
    In [42]: df.ffill()
    Out[42]: 
              A  B
    0 -1.186808 -1
    1 -0.095587 -1
    2 -1.921372 -1
    3 -0.772836 -1
    4  0.016883 -1
    5  0.350778 -1
    6  0.165055 -1
    7  1.101561  1
    8 -0.346786  1
    9 -0.186263  1
    

提交回复
热议问题