Reference previous row when iterating through dataframe

后端 未结 3 872
夕颜
夕颜 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:38

    Try this: If the first value is neither >= 1 or < -1 set to 0 or whatever you like.

    df["B"] = None
    df["B"] = np.where(df['A'] >= 1, 1,df['B'])
    df["B"] = np.where(df['A'] < -1, -1,df['B'])
    df = df.ffill().fillna(0)
    

    This solves the problem stated, But the real solution to reference previous row is use .shift() or .index() -1

提交回复
热议问题