computation
Computational tools
Statistical functions
Percent change
Series and DataFrame have a methodpct_change() to compute the percent change over a given number
of periods (using fill_method to fill NA/null values before computing
the percent change).
1 | In [1]: ser = pd.Series(np.random.randn(8)) |
1 | In [3]: df = pd.DataFrame(np.random.randn(10, 4)) |
Covariance
Series.cov() can be used to compute covariance between series
(excluding missing values).
1 | In [5]: s1 = pd.Series(np.random.randn(1000)) |
Analogously, DataFrame.cov() to compute pairwise covariances among the
series in the DataFrame, also excluding NA/null values.
::: tip Note
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.
:::
1 | In [8]: frame = pd.DataFrame(np.random.randn(1000, 5), |
DataFrame.cov also supports an optional min_periods keyword that
specifies the required minimum number of observations for each column pair
in order to have a valid result.
1 | In [10]: frame = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c']) |
Correlation
Correlation may be computed using the corr() method.
Using the method parameter, several methods for computing correlations are
provided:
| Method name | Description |
|---|---|
| pearson (default) | Standard correlation coefficient |
| kendall | Kendall Tau correlation coefficient |
| spearman | Spearman rank correlation coefficient |
All of these are currently computed using pairwise complete observations.
Wikipedia has articles covering the above correlation coefficients:
- Pearson correlation coefficient
- Kendall rank correlation coefficient
- Spearman’s rank correlation coefficient
::: tip Note
Please see the caveats associated
with this method of calculating correlation matrices in the
covariance section.
:::
1 | In [15]: frame = pd.DataFrame(np.random.randn(1000, 5), |
Note that non-numeric columns will be automatically excluded from the
correlation calculation.
Like cov, corr also supports the optional min_periods keyword:
1 | In [20]: frame = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c']) |
New in version 0.24.0.
The method argument can also be a callable for a generic correlation
calculation. In this case, it should be a single function
that produces a single value from two ndarray inputs. Suppose we wanted to
compute the correlation based on histogram intersection:
1 | # histogram intersection |
A related method corrwith() is implemented on DataFrame to
compute the correlation between like-labeled Series contained in different
DataFrame objects.
1 | In [27]: index = ['a', 'b', 'c', 'd', 'e'] |
Data ranking
The rank() method produces a data ranking with ties being
assigned the mean of the ranks (by default) for the group:
1 | In [33]: s = pd.Series(np.random.np.random.randn(5), index=list('abcde')) |
rank() is also a DataFrame method and can rank either the rows
(axis=0) or the columns (axis=1). NaN values are excluded from the
ranking.
1 | In [36]: df = pd.DataFrame(np.random.np.random.randn(10, 6)) |
rank optionally takes a parameter ascending which by default is true;
when false, data is reverse-ranked, with larger values assigned a smaller rank.
rank supports different tie-breaking methods, specified with the method
parameter:
average: average rank of tied groupmin: lowest rank in the groupmax: highest rank in the groupfirst: ranks assigned in the order they appear in the array
Window Functions
For working with data, a number of window functions are provided for
computing common window or rolling statistics. Among these are count, sum,
mean, median, correlation, variance, covariance, standard deviation, skewness,
and kurtosis.
The rolling() and expanding()
functions can be used directly from DataFrameGroupBy objects,
see the groupby docs.
::: tip Note
The API for window statistics is quite similar to the way one works with GroupBy objects, see the documentation here.
:::
We work with rolling, expanding and exponentially weighted data through the corresponding
objects, Rolling, Expanding and EWM.
1 | In [40]: s = pd.Series(np.random.randn(1000), |
These are created from methods on Series and DataFrame.
1 | In [43]: r = s.rolling(window=60) |
These object provide tab-completion of the available methods and properties.
1 | In [14]: r.<TAB> # noqa: E225, E999 |
Generally these methods all have the same interface. They all
accept the following arguments:
window: size of moving windowmin_periods: threshold of non-null data points to require (otherwise
result is NA)center: boolean, whether to set the labels at the center (default is False)
We can then call methods on these rolling objects. These return like-indexed objects:
1 | In [45]: r.mean() |
1 | In [46]: s.plot(style='k--') |

They can also be applied to DataFrame objects. This is really just syntactic
sugar for applying the moving window operator to all of the DataFrame’s columns:
1 | In [48]: df = pd.DataFrame(np.random.randn(1000, 4), |

Method summary
We provide a number of common statistical functions:
| Method | Description |
|---|---|
| count() | Number of non-null observations |
| sum() | Sum of values |
| mean() | Mean of values |
| median() | Arithmetic median of values |
| min() | Minimum |
| max() | Maximum |
| std() | Bessel-corrected sample standard deviation |
| var() | Unbiased variance |
| skew() | Sample skewness (3rd moment) |
| kurt() | Sample kurtosis (4th moment) |
| quantile() | Sample quantile (value at %) |
| apply() | Generic apply |
| cov() | Unbiased covariance (binary) |
| corr() | Correlation (binary) |
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. Suppose we wanted to
compute the mean absolute deviation on a rolling basis:
1 | In [51]: def mad(x): |

Rolling windows
Passing win_type to .rolling generates a generic rolling window computation, that is weighted according the win_type.
The following methods are available:
| Method | Description |
|---|---|
| sum() | Sum of values |
| mean() | Mean of values |
The weights used in the window are specified by the win_type keyword.
The list of recognized types are the scipy.signal window functions:
boxcartriangblackmanhammingbartlettparzenbohmanblackmanharrisnuttallbarthannkaiser(needs beta)gaussian(needs std)general_gaussian(needs power, width)slepian(needs width)exponential(needs tau).
1 | In [53]: ser = pd.Series(np.random.randn(10), |
Note that the boxcar window is equivalent to mean().
1 | In [55]: ser.rolling(window=5, win_type='boxcar').mean() |
For some windowing functions, additional parameters must be specified:
1 | In [57]: ser.rolling(window=5, win_type='gaussian').mean(std=0.1) |
::: tip Note
For .sum() with a win_type, there is no normalization done to the
weights for the window. Passing custom weights of [1, 1, 1] will yield a different
result than passing weights of [2, 2, 2], for example. When passing awin_type instead of explicitly specifying the weights, the weights are
already normalized so that the largest weight is 1.
In contrast, the nature of the .mean() calculation is
such that the weights are normalized with respect to each other. Weights
of [1, 1, 1] and [2, 2, 2] yield the same result.
:::
Time-aware rolling
New in version 0.19.0.
New in version 0.19.0 are the ability to pass an offset (or convertible) to a .rolling() method and have it produce
variable sized windows based on the passed time window. For each time point, this includes all preceding values occurring
within the indicated time delta.
This can be particularly useful for a non-regular time frequency index.
1 | In [58]: dft = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}, |
This is a regular frequency index. Using an integer window parameter works to roll along the window frequency.
1 | In [60]: dft.rolling(2).sum() |
Specifying an offset allows a more intuitive specification of the rolling frequency.
1 | In [62]: dft.rolling('2s').sum() |
Using a non-regular, but still monotonic index, rolling with an integer window does not impart any special calculation.
1 | In [63]: dft = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}, |
Using the time-specification generates variable windows for this sparse data.
1 | In [66]: dft.rolling('2s').sum() |
Furthermore, we now allow an optional on parameter to specify a column (rather than the
default of the index) in a DataFrame.
1 | In [67]: dft = dft.reset_index() |
Rolling window endpoints
New in version 0.20.0.
The inclusion of the interval endpoints in rolling window calculations can be specified with the closed
parameter:
| closed | Description | Default for |
|---|---|---|
| right | close right endpoint | time-based windows |
| left | close left endpoint | |
| both | close both endpoints | fixed windows |
| neither | 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.
1 | In [70]: df = pd.DataFrame({'x': 1}, |
Currently, this feature is only implemented for time-based windows.
For fixed windows, the closed parameter cannot be set and the rolling window will always have both endpoints closed.
Time-aware rolling vs. resampling
Using .rolling() with a time-based index is quite similar to resampling. They
both operate and perform reductive operations on time-indexed pandas objects.
When using .rolling() with an offset. The offset is a time-delta. Take a backwards-in-time looking window, and
aggregate all of the values in that window (including the end-point, but not the start-point). This is the new value
at that point in the result. These are variable sized windows in time-space for each point of the input. You will get
a same sized result as the input.
When using .resample() with an offset. Construct a new index that is the frequency of the offset. For each frequency
bin, aggregate points from the input within a backwards-in-time looking window that fall in that bin. The result of this
aggregation is the output for that frequency point. The windows are fixed size in the frequency space. Your result
will have the shape of a regular frequency between the min and the max of the original input object.
To summarize, .rolling() is a time-based window operation, while .resample() is a frequency-based window operation.
Centering windows
By default the labels are set to the right edge of the window, but acenter keyword is available so the labels can be set at the center.
1 | In [76]: ser.rolling(window=5).mean() |
Binary window functions
cov() and corr() can compute moving window statistics about
two Series or any combination of DataFrame/Series orDataFrame/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=Trueis
passed then computes the statistic for each pair of columns, returning aMultiIndexed DataFramewhoseindexare the dates in question (see the next section).
For example:
1 | In [78]: df = pd.DataFrame(np.random.randn(1000, 4), |
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 ofDataFrame 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:
::: tip 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.
:::
1 | In [82]: covs = (df[['B', 'C', 'D']].rolling(window=50) |
1 | In [84]: correls = df.rolling(window=50).corr() |
You can efficiently retrieve the time series of correlations between two
columns by reshaping and indexing:
1 | In [86]: correls.unstack(1)[('A', 'C')].plot() |

Aggregation
Once the Rolling, Expanding or EWM objects have been created, several methods are available to
perform multiple computations on the data. These operations are similar to the aggregating API,
groupby API, and resample API.
1 | In [87]: dfa = pd.DataFrame(np.random.randn(1000, 3), |
We can aggregate by passing a function to the entire DataFrame, or select a
Series (or multiple Series) via standard __getitem__.
1 | In [90]: r.aggregate(np.sum) |
As you can see, the result of the aggregation will have the selected columns, or all
columns if none are selected.
Applying multiple functions
With windowed Series you can also pass a list of functions to do
aggregation with, outputting a DataFrame:
1 | In [93]: r['A'].agg([np.sum, np.mean, np.std]) |
On a windowed DataFrame, you can pass a list of functions to apply to each
column, which produces an aggregated result with a hierarchical index:
1 | In [94]: r.agg([np.sum, np.mean]) |
Passing a dict of functions has different behavior by default, see the next
section.
Applying different functions to DataFrame columns
By passing a dict to aggregate you can apply a different aggregation to the
columns of a DataFrame:
1 | In [95]: r.agg({'A': np.sum, 'B': lambda x: np.std(x, ddof=1)}) |
The function names can also be strings. In order for a string to be valid it
must be implemented on the windowed object
1 | In [96]: r.agg({'A': 'sum', 'B': 'std'}) |
Furthermore you can pass a nested dict to indicate different aggregations on different columns.
1 | In [97]: r.agg({'A': ['sum', 'std'], 'B': ['mean', 'std']}) |
Expanding windows
A common alternative to rolling statistics is to use an expanding window,
which yields the value of the statistic with all the data available up to that
point in time.
These follow a similar interface to .rolling, with the .expanding method
returning an Expanding object.
As these calculations are a special case of rolling statistics,
they are implemented in pandas such that the following two calls are equivalent:
1 | In [98]: df.rolling(window=len(df), min_periods=1).mean()[:5] |
These have a similar set of methods to .rolling methods.
Method summary
| Function | Description |
|---|---|
| count() | Number of non-null observations |
| sum() | Sum of values |
| mean() | Mean of values |
| median() | Arithmetic median of values |
| min() | Minimum |
| max() | Maximum |
| std() | Unbiased standard deviation |
| var() | Unbiased variance |
| skew() | Unbiased skewness (3rd moment) |
| kurt() | Unbiased kurtosis (4th moment) |
| quantile() | Sample quantile (value at %) |
| apply() | Generic apply |
| cov() | Unbiased covariance (binary) |
| corr() | Correlation (binary) |
Aside from not having a window parameter, these functions have the same
interfaces as their .rolling counterparts. Like above, the parameters they
all accept are:
min_periods: threshold of non-null data points to require. Defaults to
minimum needed to compute statistic. NoNaNswill be output oncemin_periodsnon-null data points have been seen.center: boolean, whether to set the labels at the center (default is False).
::: tip Note
The output of the .rolling and .expanding methods do not return aNaN if there are at least min_periods non-null values in the current
window. For example:
1 | In [100]: sn = pd.Series([1, 2, np.nan, 3, np.nan, 4]) |
In case of expanding functions, this differs from cumsum(),cumprod(), cummax(),
and cummin(), which return NaN in the output wherever
a NaN is encountered in the input. In order to match the output of cumsum
with expanding, use fillna():
1 | In [104]: sn.expanding().sum() |
:::
An expanding window statistic will be more stable (and less responsive) than
its rolling window counterpart as the increasing window size decreases the
relative impact of an individual data point. As an example, here is themean() output for the previous time series dataset:
1 | In [107]: s.plot(style='k--') |

Exponentially weighted windows
A related set of functions are exponentially weighted versions of several of
the above statistics. A similar interface to .rolling and .expanding is accessed
through the .ewm method to receive an EWM object.
A number of expanding EW (exponentially weighted)
methods are provided:
| Function | Description |
|---|---|
| mean() | EW moving average |
| var() | EW moving variance |
| std() | EW moving standard deviation |
| corr() | EW moving correlation |
| cov() | EW moving covariance |
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.
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
::: tip 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_{t-1}\).
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 since version 0.18.0
it has been possible to pass \(\alpha\) directly, it’s often easier
to think about either the span, center of mass (com) or half-life
of an EW moment:
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.
Here is an example for a univariate time series:
1 | In [109]: s.plot(style='k--') |

EWM has a min_periods argument, which has the same
meaning it does for all the .expanding and .rolling methods:
no output values will be set until at least min_periods non-null values
are encountered in the (expanding) window.
EWM 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 asewmvar(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.




