Windowing Operations¶
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:
In [3]: for window in s.rolling(window=2):
...: print(window)
...:
0 0
dtype: int64
0 0
1 1
dtype: int64
1 1
2 2
dtype: int64
2 2
3 3
dtype: int64
3 3
4 4
dtype: int64
Overview¶
pandas supports 4 types of windowing operations:
Rolling window: Generic fixed or variable sliding window over the values.
Weighted window: Weighted, nonrectangular 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 timebased windows 
Supports chained groupby 
Supports table method 

Rolling window 


Yes 
Yes 
Yes (as of version 1.3) 
Weighted window 


No 
No 
No 
Expanding window 


No 
Yes 
Yes (as of version 1.3) 
Exponentially Weighted window 


No 
Yes (as of version 1.2) 
No 
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('20200101', periods=5, freq='1D'))
In [5]: s.rolling(window='2D').sum()
Out[5]:
20200101 0.0
20200102 1.0
20200103 3.0
20200104 5.0
20200105 7.0
Freq: D, dtype: float64
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()
Out[7]:
B
A
a 0 0.0
2 2.0
4 6.0
b 1 1.0
3 4.0
Note
Windowing operations currently only support numeric data (integer and float)
and will always return float64
values.
Warning
Some windowing aggregation, mean
, sum
, var
and std
methods may suffer from numerical
imprecision due to the underlying windowing algorithms accumulating sums. When values differ
with magnitude \(1/np.finfo(np.double).eps\) this results in truncation. It must be
noted, that large values may have an impact on windows, which do not include these values. Kahan summation is used
to compute the rolling sums to preserve accuracy as much as possible.
New in version 1.3.
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]: def weighted_mean(x):
...: arr = np.ones((1, x.shape[1]))
...: arr[:, :2] = (x[:, :2] * x[:, 2]).sum(axis=0) / x[:, 2].sum()
...: return arr
...:
In [9]: df = pd.DataFrame([[1, 2, 0.6], [2, 3, 0.4], [3, 4, 0.2], [4, 5, 0.7]])
In [10]: df.rolling(2, method="table", min_periods=0).apply(weighted_mean, raw=True, engine="numba") # noqa:E501
Out[10]:
0 1 2
0 1.000000 2.000000 1.0
1 1.800000 2.000000 1.0
2 3.333333 2.333333 1.0
3 1.555556 7.000000 1.0
All windowing operations support a min_periods
argument that dictates the minimum amount of
nonnp.nan
values a window must have; otherwise, the resulting value is np.nan
.
min_peridos
defaults to 1 for timebased windows and window
for fixed windows
In [11]: s = pd.Series([np.nan, 1, 2, np.nan, np.nan, 3])
In [12]: s.rolling(window=3, min_periods=1).sum()
Out[12]:
0 NaN
1 1.0
2 3.0
3 3.0
4 2.0
5 3.0
dtype: float64
In [13]: s.rolling(window=3, min_periods=2).sum()
Out[13]:
0 NaN
1 NaN
2 3.0
3 3.0
4 NaN
5 NaN
dtype: float64
# Equivalent to min_periods=3
In [14]: s.rolling(window=3, min_periods=None).sum()
Out[14]:
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
dtype: float64
Additionally, all windowing operations supports the aggregate
method for returning a result
of multiple aggregations applied to a window.
In [15]: df = pd.DataFrame({"A": range(5), "B": range(10, 15)})
In [16]: df.expanding().agg([np.sum, np.mean, np.std])
Out[16]:
A B
sum mean std sum mean std
0 0.0 0.0 NaN 10.0 10.0 NaN
1 1.0 0.5 0.707107 21.0 10.5 0.707107
2 3.0 1.0 1.000000 33.0 11.0 1.000000
3 6.0 1.5 1.290994 46.0 11.5 1.290994
4 10.0 2.0 1.581139 60.0 12.0 1.581139
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 [17]: times = ['20200101', '20200103', '20200104', '20200105', '20200129']
In [18]: s = pd.Series(range(5), index=pd.DatetimeIndex(times))
In [19]: s
Out[19]:
20200101 0
20200103 1
20200104 2
20200105 3
20200129 4
dtype: int64
# Window with 2 observations
In [20]: s.rolling(window=2).sum()
Out[20]:
20200101 NaN
20200103 1.0
20200104 3.0
20200105 5.0
20200129 7.0
dtype: float64
# Window with 2 days worth of observations
In [21]: s.rolling(window='2D').sum()
Out[21]:
20200101 0.0
20200103 1.0
20200104 3.0
20200105 5.0
20200129 4.0
dtype: float64
For all supported aggregation functions, see Rolling window functions.
Centering windows¶
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 [22]: s = pd.Series(range(10))
In [23]: s.rolling(window=5).mean()
Out[23]:
0 NaN
1 NaN
2 NaN
3 NaN
4 2.0
5 3.0
6 4.0
7 5.0
8 6.0
9 7.0
dtype: float64
In [24]: s.rolling(window=5, center=True).mean()
Out[24]:
0 NaN
1 NaN
2 2.0
3 3.0
4 4.0
5 5.0
6 6.0
7 7.0
8 NaN
9 NaN
dtype: float64
Rolling window endpoints¶
The inclusion of the interval endpoints in rolling window calculations can be specified with the closed
parameter:
Value 
Behavior 


close right endpoint 

close left endpoint 

close both endpoints 

open endpoints 
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 [25]: 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 [26]: df["right"] = df.rolling("2s", closed="right").x.sum() # default
In [27]: df["both"] = df.rolling("2s", closed="both").x.sum()
In [28]: df["left"] = df.rolling("2s", closed="left").x.sum()
In [29]: df["neither"] = df.rolling("2s", closed="neither").x.sum()
In [30]: df
Out[30]:
x right both left neither
20130101 09:00:01 1 1.0 1.0 NaN NaN
20130101 09:00:02 1 2.0 2.0 1.0 1.0
20130101 09:00:03 1 2.0 3.0 2.0 1.0
20130101 09:00:04 1 2.0 3.0 2.0 1.0
20130101 09:00:06 1 1.0 2.0 1.0 NaN
Custom window rolling¶
New in version 1.0.
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 will automatically be passed to get_window_bounds
and the defined method must
always accept these arguments.
For example, if we have the following :class:DataFrame
:
In [31]: use_expanding = [True, False, True, False, True]
In [32]: use_expanding
Out[32]: [True, False, True, False, True]
In [33]: df = pd.DataFrame({"values": range(5)})
In [34]: df
Out[34]:
values
0 0
1 1
2 2
3 3
4 4
and we want to use an expanding window where use_expanding
is True
otherwise a window of size
1, we can create the following BaseIndexer
subclass:
In [2]: from pandas.api.indexers import BaseIndexer
...:
...: class CustomIndexer(BaseIndexer):
...:
...: def get_window_bounds(self, num_values, min_periods, center, closed):
...: start = np.empty(num_values, dtype=np.int64)
...: end = np.empty(num_values, dtype=np.int64)
...: for i in range(num_values):
...: if self.use_expanding[i]:
...: start[i] = 0
...: end[i] = i + 1
...: else:
...: start[i] = i
...: end[i] = i + self.window_size
...: return start, end
...:
In [3]: indexer = CustomIndexer(window_size=1, use_expanding=use_expanding)
In [4]: df.rolling(indexer).sum()
Out[4]:
values
0 0.0
1 1.0
2 3.0
3 3.0
4 10.0
You can view other examples of BaseIndexer
subclasses here
New in version 1.1.
One subclass of note within those examples is the VariableOffsetWindowIndexer
that allows
rolling operations over a nonfixed offset like a BusinessDay
.
In [35]: from pandas.api.indexers import VariableOffsetWindowIndexer
In [36]: df = pd.DataFrame(range(10), index=pd.date_range("2020", periods=10))
In [37]: offset = pd.offsets.BDay(1)
In [38]: indexer = VariableOffsetWindowIndexer(index=df.index, offset=offset)
In [39]: df
Out[39]:
0
20200101 0
20200102 1
20200103 2
20200104 3
20200105 4
20200106 5
20200107 6
20200108 7
20200109 8
20200110 9
In [40]: df.rolling(indexer).sum()
Out[40]:
0
20200101 0.0
20200102 1.0
20200103 2.0
20200104 3.0
20200105 7.0
20200106 12.0
20200107 6.0
20200108 7.0
20200109 8.0
20200110 9.0
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 forwardlooking rolling window computations.
FixedForwardWindowIndexer
class is available for this purpose.
This BaseIndexer
subclass implements a closed fixedwidth
forwardlooking rolling window, and we can use it as follows:
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 [41]: def mad(x):
....: return np.fabs(x  x.mean()).mean()
....:
In [42]: s = pd.Series(range(10))
In [43]: s.rolling(window=4).apply(mad, raw=True)
Out[43]:
0 NaN
1 NaN
2 NaN
3 1.0
4 1.0
5 1.0
6 1.0
7 1.0
8 1.0
9 1.0
dtype: float64
Numba engine¶
New in version 1.0.
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
).
Numba will be applied in potentially two routines:
If
func
is a standard Python function, the engine will JIT the passed function.func
can also be a JITed function in which case the engine will not JIT the function again.The engine will JIT the for loop where the apply function is applied to each window.
New in version 1.3.
mean
, median
, max
, min
, and sum
also support the engine
and engine_kwargs
arguments.
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. Currently only nogil
, nopython
, and parallel
are supported,
and their default values are set to False
, True
and False
respectively.
Note
In terms of performance, the first time a function is run using the Numba engine will be slow as Numba will have some function compilation overhead. However, the compiled functions are cached, and subsequent calls will be fast. In general, the Numba engine is performant with a larger amount of data points (e.g. 1+ million).
In [1]: data = pd.Series(range(1_000_000))
In [2]: roll = data.rolling(10)
In [3]: def f(x):
...: return np.sum(x) + 5
# Run the first time, compilation time will affect performance
In [4]: %timeit r 1 n 1 roll.apply(f, engine='numba', raw=True) # noqa: E225, E999
1.23 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
# Function is cached and performance will improve
In [5]: %timeit roll.apply(f, engine='numba', raw=True)
188 ms ± 1.93 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [6]: %timeit roll.apply(f, engine='cython', raw=True)
3.92 s ± 59 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Binary window functions¶
cov()
and corr()
can compute moving window statistics about
two Series
or any combination of DataFrame
/Series
or
DataFrame
/DataFrame
. Here is the behavior in each case:
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 argumentpairwise=True
is passed then computes the statistic for each pair of columns, returning aMultiIndexed DataFrame
whoseindex
are the dates in question (see the next section).
For example:
In [44]: df = pd.DataFrame(
....: np.random.randn(10, 4),
....: index=pd.date_range("20200101", periods=10),
....: columns=["A", "B", "C", "D"],
....: )
....:
In [45]: df = df.cumsum()
In [46]: df2 = df[:4]
In [47]: df2.rolling(window=2).corr(df2["B"])
Out[47]:
A B C D
20200101 NaN NaN NaN NaN
20200102 1.0 1.0 1.0 1.0
20200103 1.0 1.0 1.0 1.0
20200104 1.0 1.0 1.0 1.0
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 movingwindow 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:
Note
Missing values are ignored and each entry is computed using the pairwise complete observations. Please see the covariance section for caveats associated with this method of calculating covariance and correlation matrices.
In [48]: covs = (
....: df[["B", "C", "D"]]
....: .rolling(window=4)
....: .cov(df[["A", "B", "C"]], pairwise=True)
....: )
....:
In [49]: covs
Out[49]:
B C D
20200101 A NaN NaN NaN
B NaN NaN NaN
C NaN NaN NaN
20200102 A NaN NaN NaN
B NaN NaN NaN
... ... ... ...
20200109 B 0.342006 0.230190 0.052849
C 0.230190 1.575251 0.082901
20200110 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]
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.
In [50]: s = pd.Series(range(10))
In [51]: s.rolling(window=5).mean()
Out[51]:
0 NaN
1 NaN
2 NaN
3 NaN
4 2.0
5 3.0
6 4.0
7 5.0
8 6.0
9 7.0
dtype: float64
In [52]: s.rolling(window=5, win_type="triang").mean()
Out[52]:
0 NaN
1 NaN
2 NaN
3 NaN
4 2.0
5 3.0
6 4.0
7 5.0
8 6.0
9 7.0
dtype: float64
# Supplementary Scipy arguments passed in the aggregation function
In [53]: s.rolling(window=5, win_type="gaussian").mean(std=0.1)
Out[53]:
0 NaN
1 NaN
2 NaN
3 NaN
4 2.0
5 3.0
6 4.0
7 5.0
8 6.0
9 7.0
dtype: float64
For all supported aggregation functions, see Weighted window functions.
Expanding window¶
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:
In [54]: df = pd.DataFrame(range(5))
In [55]: df.rolling(window=len(df), min_periods=1).mean()
Out[55]:
0
0 0.0
1 0.5
2 1.0
3 1.5
4 2.0
In [56]: df.expanding(min_periods=1).mean()
Out[56]:
0
0 0.0
1 0.5
2 1.0
3 1.5
4 2.0
For all supported aggregation functions, see Expanding window functions.
Exponentially Weighted window¶
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
where \(x_t\) is the input, \(y_t\) is the result and the \(w_i\) are the weights.
For all supported aggregation functions, see Exponentiallyweighted window functions.
The EW functions support two variants of exponential weights.
The default, adjust=True
, uses the weights \(w_i = (1  \alpha)^i\)
which gives
When adjust=False
is specified, moving averages are calculated as
which is equivalent to using weights
Note
These equations are sometimes written in terms of \(\alpha' = 1  \alpha\), e.g.
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
:
Noting that the denominator is a geometric series with initial term equal to 1 and a ratio of \(1  \alpha\) we have
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 \(y_0 = x_0\) and
\(y_t = \alpha x_t + (1  \alpha) y_{t1}\).
Therefore, there is an assumption that \(x_0\) is not an ordinary value
but rather an exponentially weighted moment of the infinite series up to that
point.
One must have \(0 < \alpha \leq 1\), and while it is possible to pass \(\alpha\) directly, it’s often easier to think about either the span, center of mass (com) or halflife of an EW moment:
One must specify precisely one of span, center of mass, halflife and alpha to the EW functions:
Span corresponds to what is commonly called an “Nday EW moving average”.
Center of mass has a more physical interpretation and can be thought of in terms of span: \(c = (s  1) / 2\).
Halflife is the period of time for the exponential weight to reduce to one half.
Alpha specifies the smoothing factor directly.
New in version 1.1.0.
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
.
In [57]: df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]})
In [58]: df
Out[58]:
B
0 0.0
1 1.0
2 2.0
3 NaN
4 4.0
In [59]: times = ["20200101", "20200103", "20200110", "20200115", "20200117"]
In [60]: df.ewm(halflife="4 days", times=pd.DatetimeIndex(times)).mean()
Out[60]:
B
0 0.000000
1 0.585786
2 1.523889
3 1.523889
4 3.233686
The following formula is used to compute exponentially weighted mean with an input vector of times:
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
Whereas if ignore_na=True
, the weighted average would be calculated as
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
(For \(w_i = 1\), this reduces to the usual \(N / (N  1)\) factor, with \(N = t + 1\).) See Weighted Sample Variance on Wikipedia for further details.