简体   繁体   中英

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.

Let's try, first find where 'Increase' then create groups based on 'Decrease', then sum and check for count of 2 increases.

df['Increased Twice?'] = ((df['Price Change'] == 'Increase')\
                          .groupby((df['Price Change'] == 'Decrease').cumsum())\
                          .cumsum() == 2).astype(int)

Output:

  ProductID Price Change  Increased Twice?
0      2d3Q     Increase                 0
1      2d3Q     Increase                 1
2      2d3Q     Decrease                 0
3      2d3Q     Increase                 0
4      2d3Q     Increase                 1
5      2d3Q     Decrease                 0
6      2d3Q     Increase                 0
7      2d3Q     Increase                 1

Try numpy.where() :

import numpy as np

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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