Home > Software design >  Pandas: conditional cumsum with bandwidth function
Pandas: conditional cumsum with bandwidth function

Time:04-07

I want to have a conditional column created with the underlying logic: if signal is 1 I add 5 to the current value, if its negative I remove 5 and if its 0 I do nothing. With .cumsum() on pandas its clear for me how to do it, but problem is that I want to restrict this in case value hits a certain bandwidth (in this example 45-55). In the example below once value hits 55, another positive signal will not increase it, but wait until negative signal.

Does anyone know how I can add this theoretical bandwidth in my code?

Before:

signal value
1 50
0 50
-1 50
1 50
0 50
1 50
-1 50

After:

signal value value created
1 50 55
0 50 50
-1 50 45
1 50 55
0 50 50
1 50 55
-1 50 45

CodePudding user response:

You description doesn't seem to match the provided output. From the description, here is what I understood:

df['value created'] = (df['value']
                       # add 5 to the current value,
                       # if its negative I remove 5 
                       # if its 0 I do nothing
                       .add(df['signal'].mul(5))
                       # restrict this in case value hits a certain bandwidth
                       # (in this example 45-55)
                       .clip(lower=45, upper=55)
                      )

output:

   signal  value  value created
0       1     50             55
1       0     50             50
2      -1     50             45
3       1     50             55
4       0     50             50
5       1     50             55
6      -1     50             45
  • Related