Home > Net >  How to do rolling subtraction repeatedly with Pandas Dataframe
How to do rolling subtraction repeatedly with Pandas Dataframe

Time:11-19

How to do rolling subtraction repeatedly with a Pandas Dataframe?

I have a dataframe that looks like this:

value
100
1
4
10
5
3

I want to repeatedly subtract previous value with current value. I want the following output:

100
99
95
85
80
77

How can I do this? If I have multiple columns in the dataframe, how can I apply the same operation to all of the columns?

CodePudding user response:

A vectorized solution:

-(df['value']).cumsum()   df['value'].iat[0]*2

Output:

0    100
1     99
2     95
3     85
4     80
5     77
Name: value, dtype: int64

CodePudding user response:

Combine expanding with np.subtract.reduce:

df.value.expanding(1).agg(np.subtract.reduce)

0    100.0
1     99.0
2     95.0
3     85.0
4     80.0
5     77.0
Name: value, dtype: float64
  • Related