简体   繁体   中英

How to do rolling subtraction repeatedly with Pandas Dataframe

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?

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

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

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