Ha An Tran
Ha An Tran

Reputation: 357

Calculate the slope at every point in time series

I have a time series dataframe that shows the production of a wind park every 15 minutes, something like this:

2013-01-01 00:00:00+00:00   4732.154785
2013-01-01 00:15:00+00:00   4709.465820
2013-01-01 00:30:00+00:00   4646.984863
2013-01-01 00:45:00+00:00   4569.866211
2013-01-01 01:00:00+00:00   4559.160156
2013-01-01 01:15:00+00:00   4467.170898
2013-01-01 01:30:00+00:00   4413.409180
2013-01-01 01:45:00+00:00   4316.044922
2013-01-01 02:00:00+00:00   4279.421875
2013-01-01 02:15:00+00:00   4149.459961
......................................

2015-01-02 03:30:00+00:00   3878.446045
2015-01-02 03:45:00+00:00   3806.699951
2015-01-02 04:00:00+00:00   3730.960938
2015-01-02 04:15:00+00:00   3639.235107
2015-01-02 04:30:00+00:00   3592.825928

At each point of the dataframe, I want to calculate the slope of the line connecting the production of the last 30 minutes and the next 30 minutes. For example, at 2013-01-01 00:45:00+00:00, I will look at values at 2013-01-01 00:15:00+00:00 and 2013-01-01 01:15:00+00:00

I have check the diff in pandas series, but isn't it just calculate the difference between two nearby timestamps?

Upvotes: 0

Views: 608

Answers (1)

Georgina Skibinski
Georgina Skibinski

Reputation: 13387

I assume we start with:

>>> df
                   dt         prod
0 2013-01-01 00:00:00  4732.154785
1 2013-01-01 00:15:00  4709.465820
2 2013-01-01 00:30:00  4646.984863
3 2013-01-01 00:45:00  4569.866211
4 2013-01-01 01:00:00  4559.160156
5 2013-01-01 01:15:00  4467.170898
6 2013-01-01 01:30:00  4413.409180
7 2013-01-01 01:45:00  4316.044922
8 2013-01-01 02:00:00  4279.421875
>>> df.dtypes
dt      datetime64[ns]
prod           float64
dtype: object

In case if your data is not sorted - start with:

df=df.sort_values("dt", ascending=1)

Then to get prev/next elements, as per "dt":

>>> df["prod_prev"] = df["prod"].shift(1)
>>> df["prod_next"] = df["prod"].shift(-1)
>>> df
                   dt         prod    prod_prev    prod_next
0 2013-01-01 00:00:00  4732.154785          NaN  4709.465820
1 2013-01-01 00:15:00  4709.465820  4732.154785  4646.984863
2 2013-01-01 00:30:00  4646.984863  4709.465820  4569.866211
3 2013-01-01 00:45:00  4569.866211  4646.984863  4559.160156
4 2013-01-01 01:00:00  4559.160156  4569.866211  4467.170898
5 2013-01-01 01:15:00  4467.170898  4559.160156  4413.409180
6 2013-01-01 01:30:00  4413.409180  4467.170898  4316.044922
7 2013-01-01 01:45:00  4316.044922  4413.409180  4279.421875
8 2013-01-01 02:00:00  4279.421875  4316.044922          NaN


Upvotes: 1

Related Questions