Search code examples
pythonpandascumsum

Need help trying to reset cum sum value back to zero when criteria is not meet by comparing values in previous rows from another column


I am trying to put a 1 or Yes if Price Increase twice in a row. I tried using cumsum, but I can't figure out how to reset the value back to zero if it isn't true

df["Increased Twice?"] = ((df.shift(1)["Price Change"] == df3bet["Price Change"])).cumsum()

This the result from the code I have

ProductID  Price Change  Increased Twice?
 2d3Q       Increase            0
 2d3Q       Increase            1
 2d3Q       Decrease            1
 2d3Q       Increase            1
 2d3Q       Increase            2
 2d3Q       Decrease            2
 2d3Q       Increase            2
 2d3Q       Increase            3 
 

This is what I want

ProductID  Price Change  Increased Twice?
 2d3Q       Increase            0
 2d3Q       Increase            1
 2d3Q       Decrease            0
 2d3Q       Increase            0
 2d3Q       Increase            1
 2d3Q       Decrease            0
 2d3Q       Increase            0
 2d3Q       Increase            1 

I have also tried some different if then statements, but I haven't it gotten to work.


Solution

  • Try numpy.where():

    import numpy as np
    
    df['Increased Twice?'] = np.where(df['Price Change'] == df.shift(1)['Price Change'], 1, 0)