pandas contains a compact set of APIs for performing windowing operations - an operation that performs
an aggregation over a sliding partition of values. The API functions similarly to the groupby API
in that Series and DataFrame call the windowing method with
necessary parameters and then subsequently call the aggregation function.
In [1]: s=pd.Series(range(
5
))
In [2]:
s
.
rolling
(
window
=
2
)
.
sum
()
Out[2]:
0 NaN
1 1.0
2 3.0
3 5.0
4 7.0
dtype: float64
The windows are comprised by looking back the length of the window from the current observation.
The result above can be derived by taking the sum of the following windowed partitions of data:
Rolling window: Generic fixed or variable sliding window over the values.
Weighted window: Weighted, non-rectangular window supplied by the scipy.signal library.
Expanding window: Accumulating window over the values.
Exponentially Weighted window: Accumulating and exponentially weighted window over the values.
Concept
Method
Returned Object
Supports time-based windows
Supports chained groupby
Supports table method
Supports online operations
Rolling window
rolling
pandas.typing.api.Rolling
Yes
Yes
Yes (as of version 1.3)
No
Weighted window
rolling
As noted above, some operations support specifying a window based on a time offset:
In [4]: s=pd.Series(range(5),index=pd.date_range('2020-01-01',periods=5,freq='1D'))In [5]: s.rolling(window='2D').sum
Additionally, some methods support chaining a groupby operation with a windowing operation
which will first group the data by the specified keys and then perform a windowing operation per group.
In [6]: df=pd.DataFrame({'A':['a','b','a','b','a'],'B':range(5)})In [7]: df.groupby('A').expanding().sum
Some windowing operations also support the method='table' option in the constructor which
performs the windowing operation over an entire DataFrame instead of a single column or row at a time.
This can provide a useful performance benefit for a DataFrame with many columns or rows
(with the corresponding axis argument) or the ability to utilize other columns during the windowing
operation. The method='table' option can only be used if engine='numba' is specified
in the corresponding method call.
For example, a weighted mean calculation can
be calculated with apply() by specifying a separate column of weights.
In [8]: defweighted_mean(x): ...: arr=np.ones((1,x.shape[1])) ...: arr[:,:2]=(x[:,:2]*x[:,
Some windowing operations also support an online method after constructing a windowing object
which returns a new object that supports passing in new DataFrame or Series objects
to continue the windowing calculation with the new values (i.e. online calculations).
The methods on this new windowing objects must call the aggregation method first to “prime” the initial
state of the online calculation. Then, new DataFrame or Series objects can be passed in
the update argument to continue the windowing calculation.
In [11]: df=pd.DataFrame([[1,2,0.6],[2,3,0.4],[3,4,0.2],[4,5,0.7]])In [12]: df.ewm
All windowing operations support a min_periods argument that dictates the minimum amount of
non-np.nan values a window must have; otherwise, the resulting value is np.nan.
min_periods defaults to 1 for time-based windows and window for fixed windows
In [16]: s=pd.Series([np.nan,1,2,np.nan,np.nan,3])In [17]: s.rolling(window=3,min_periods=1).
Additionally, all windowing operations supports the aggregate method for returning a result
of multiple aggregations applied to a window.
In [20]: df=pd.DataFrame({"A":range(5),"B":range(10,15)})In [21]: df.expanding().agg(["sum","mean","std"])Out[21]: A B
Rolling window
Generic rolling windows support specifying windows as a fixed number of observations or variable
number of observations based on an offset. If a time based offset is provided, the corresponding
time based index must be monotonic.
In [22]: times=['2020-01-01','2020-01-03','2020-01-04','2020-01-05','2020-01-29']In [23]: s=pd.Series(range(5),index=pd.DatetimeIndex(times))In [24]: sOut[24]: 2020-01-01 02020-01-03 12020-01-04 22020-01-05 32020-01-29 4dtype: int64# Window with 2 observationsIn [25]: s.rolling(window=2).sum()Out[25]: 2020-01-01 NaN2020-01-03 1.02020-01-04 3.02020-01-05 5.02020-01-29 7.0dtype: float64# Window with 2 days worth of observationsIn [26]: s.rolling(window='2D').sum()Out[26]: 2020-01-01 0.02020-01-03 1.02020-01-04 3.02020-01-05 5.02020-01-29 4.0dtype: float64
By default the labels are set to the right edge of the window, but a
center keyword is available so the labels can be set at the center.
In [27]: s=pd.Series(range(10))In [28]: s.rolling(window=5).mean()Out[28]: 0 NaN1 NaN2 NaN
Rolling window endpoints
The inclusion of the interval endpoints in rolling window calculations can be specified with the closed
parameter:
Value
Behavior
'right'
close right endpoint
'left'
Custom window rolling
In addition to accepting an integer or offset as a window argument, rolling also accepts
a BaseIndexer subclass that allows a user to define a custom method for calculating window bounds.
The BaseIndexer subclass will need to define a get_window_bounds method that returns
a tuple of two arrays, the first being the starting indices of the windows and second being the
ending indices of the windows. Additionally, num_values, min_periods, center, closed
and step will automatically be passed to and the defined method must
always accept these arguments.
Rolling apply
The apply() function takes an extra func argument and performs
generic rolling computations. The func argument should be a single function
that produces a single value from an ndarray input. raw specifies whether
the windows are cast as Series objects (raw=False) or ndarray objects (raw=True).
In [61]: defmad
Numba engine
Additionally, apply() can leverage Numba
if installed as an optional dependency. The apply aggregation can be executed using Numba by specifying
engine='numba' and engine_kwargs arguments (raw must also be set to True).
See enhancing performance with Numba for general usage of the arguments and performance considerations.
Numba will be applied in potentially two routines:
If func is a standard Python function, the engine will JIT the passed function. can also be a JITed function in which case the engine will not JIT the function again.
Binary window functions
cov() and corr() can compute moving window statistics about
two Series or any combination of DataFrame/Series or
DataFrame/. Here is the behavior in each case:
Computing rolling pairwise covariances and correlations
In financial data analysis and other fields it’s common to compute covariance
and correlation matrices for a collection of time series. Often one is also
interested in moving-window covariance and correlation matrices. This can be
done by passing the pairwise keyword argument, which in the case of
DataFrame inputs will yield a MultiIndexed DataFrame whose index are the dates in
question. In the case of a single DataFrame argument the pairwise argument
can even be omitted:
Weighted window
The win_type argument in .rolling generates a weighted windows that are commonly used in filtering
and spectral estimation. win_type must be string that corresponds to a scipy.signal window function.
Scipy must be installed in order to use these windows, and supplementary arguments
that the Scipy window methods take must be specified in the aggregation function.
An expanding window yields the value of an aggregation statistic with all the data available up to that
point in time. Since these calculations are a special case of rolling statistics,
they are implemented in pandas such that the following two calls are equivalent:
An exponentially weighted window is similar to an expanding window but with each prior point
being exponentially weighted down relative to the current point.
In general, a weighted moving average is calculated as
yt=∑i=0twi∑i=0twixt−i,
where xt is the input, yt is the result and the wi
are the weights.
When adjust=False is specified, moving averages are calculated as
y0yt=x0=(1−α)yt−1+αxt,
which is equivalent to using weights
wi={α(1−α)i(1−α)iif i<tif i=t.
The difference between the above two variants arises because we are
dealing with series which have finite history. Consider a series of infinite
history, with adjust=True:
which is the same expression as adjust=False above and therefore
shows the equivalence of the two variants for infinite series.
When adjust=False, we have y0=x0 and
yt=αxt+(1−α)yt−1.
Therefore, there is an assumption that is not an ordinary value
but rather an exponentially weighted moment of the infinite series up to that
point.
One must have 0<α≤1, and while it is possible to pass
α directly, it’s often easier to think about either the
span, center of mass (com) or half-life of an EW moment:
α=⎩⎨⎧s+12,1+c1,1−exphlog0.5,for spans≥1for center of massc≥0for half-lifeh>0
One must specify precisely one of span, center of mass, half-life
and alpha to the EW functions:
Span corresponds to what is commonly called an “N-day EW moving average”.
Center of mass has a more physical interpretation and can be thought of
in terms of span: c=(s−1)/2.
Half-life is the period of time for the exponential weight to reduce to
one half.
Alpha specifies the smoothing factor directly.
You can also specify halflife in terms of a timedelta convertible unit to specify the amount of
time it takes for an observation to decay to half its value when also specifying a sequence
of times.
The following formula is used to compute exponentially weighted mean with an input vector of times:
yt=∑i=0t0.5λtt−ti∑i=0t0.5λtt−tixt−i,
ExponentialMovingWindow also has an ignore_na argument, which determines how
intermediate null values affect the calculation of the weights.
When ignore_na=False (the default), weights are calculated based on absolute
positions, so that intermediate null values affect the result.
When ignore_na=True,
weights are calculated by ignoring intermediate null values.
For example, assuming adjust=True, if ignore_na=False, the weighted
average of 3,NaN,5 would be calculated as
(1−α)2+1(1−α)2⋅3+1⋅5.
Whereas if ignore_na=True, the weighted average would be calculated as
(1−α)+1(1−α)⋅3+1⋅5.
The var(), std(), and cov() functions have a bias argument,
specifying whether the result should contain biased or unbiased statistics.
For example, if bias=True, ewmvar(x) is calculated as
ewmvar(x)=ewma(x**2)-ewma(x)**2;
whereas if bias=False (the default), the biased variance statistics
are scaled by debiasing factors
(∑i=0twi)2−∑i=0twi2(∑i=0twi)2.
(For wi=1, this reduces to the usual N/(N−1) factor,
with N=t+1.)
See
on Wikipedia for further details.
For example, having the right endpoint open is useful in many problems that require that there is no contamination
from present information back to past information. This allows the rolling window to compute statistics
“up to that point in time”, but not including that point in time.
In [34]: df=pd.DataFrame( ....: {"x":1}, ....: index=[ ....: pd.Timestamp("20130101 09:00:01"), ....: pd.Timestamp("20130101 09:00:02"), ....: pd.Timestamp("20130101 09:00:03"), ....: pd.Timestamp("20130101 09:00:04"), ....: pd.Timestamp("20130101 09:00:06"), ....: ], ....: ) ....: In [35]: df["right"]=df.rolling("2s",closed="right").x.sum()# defaultIn [36]: df["both"]=df.rolling("2s",closed="both").x.sum()In [37]: df["left"]=df.rolling("2s",closed="left").x.sum()In [38]: df["neither"]=df.rolling("2s",closed="neither").x.sum()In [39]: dfOut[39]: x right both left neither2013-01-01 09:00:01 1 1.0 1.0 NaN NaN2013-01-01 09:00:02 1 2.0 2.0 1.0 1.02013-01-01 09:00:03 1 2.0 3.0 2.0 1.02013-01-01 09:00:04 1 2.0 3.0 2.0 1.02013-01-01 09:00:06 1 1.0 2.0 1.0 NaN
You can view other examples of BaseIndexer subclasses here
One subclass of note within those examples is the VariableOffsetWindowIndexer that allows
rolling operations over a non-fixed offset like a BusinessDay.
For some problems knowledge of the future is available for analysis. For example, this occurs when
each data point is a full time series read from an experiment, and the task is to extract underlying
conditions. In these cases it can be useful to perform forward-looking rolling window computations.
FixedForwardWindowIndexer class is available for this purpose.
This BaseIndexer subclass implements a closed fixed-width
forward-looking rolling window, and we can use it as follows:
The engine will JIT the for loop where the apply function is applied to each window.
The engine_kwargs argument is a dictionary of keyword arguments that will be passed into the
numba.jit decorator.
These keyword arguments will be applied to both the passed function (if a standard Python function)
and the apply for loop over each window.
mean, median, max, min, and sum also support the engine and engine_kwargs arguments.
DataFrame
two Series: compute the statistic for the pairing.
DataFrame/Series: compute the statistics for each column of the DataFrame
with the passed Series, thus returning a DataFrame.
DataFrame/DataFrame: by default compute the statistic for matching column
names, returning a DataFrame. If the keyword argument pairwise=True is
passed then computes the statistic for each pair of columns, returning a DataFrame with a
MultiIndex whose values are the dates in question (see the next section).
For example:
In [64]: df=pd.DataFrame( ....: np.random.randn(10,4), ....: index=pd.date_range("2020-01-01",periods=10), ....: columns=["A","B","C","D"], ....: ) ....: In [65]: df=df.cumsum()In [66]: df2=df[:4]In [67]: df2.rolling(window=2).corr(df2["B"])Out[67]: A B C D2020-01-01 NaN NaN NaN NaN2020-01-02 -1.0 1.0 -1.0 1.02020-01-03 1.0 1.0 1.0 -1.02020-01-04 -1.0 1.0 1.0 -1.0
Assuming the missing data are missing at random this results in an estimate
for the covariance matrix which is unbiased. However, for many applications
this estimate may not be acceptable because the estimated covariance matrix
is not guaranteed to be positive semi-definite. This could lead to
estimated correlations having absolute values which are greater than one,
and/or a non-invertible covariance matrix. See Estimation of covariance
matrices
for more details.
In [68]: covs=( ....: df[["B","C","D"]] ....: .rolling(window=4) ....: .cov(df[["A","B","C"]],pairwise=True) ....: ) ....: In [69]: covsOut[69]: B C D2020-01-01 A NaN NaN NaN B NaN NaN NaN C NaN NaN NaN2020-01-02 A NaN NaN NaN B NaN NaN NaN... ... ... ...2020-01-09 B 0.342006 0.230190 0.052849 C 0.230190 1.575251 0.0829012020-01-10 A -0.333945 0.006871 -0.655514 B 0.649711 0.430860 0.469271 C 0.430860 0.829721 0.055300[30 rows x 3 columns]