pandas.core.window.Rolling.cov¶
Calculate the rolling sample covariance.
- param other
- Series, DataFrame, or ndarray, optional
If not supplied then will default to self and produce pairwise output.
- param pairwise
- bool, default None
If False then only matching columns between self and other will be used and the output will be a DataFrame. If True then all pairwise combinations will be calculated and the output will be a MultiIndexed DataFrame in the case of DataFrame inputs. In the case of missing elements, only complete pairwise observations will be used.
- param ddof
- int, default 1
Delta Degrees of Freedom. The divisor used in calculations is
N - ddof
, whereN
represents the number of elements. **kwargs Keyword arguments to be passed into func.- return
Series or DataFrame Return type is determined by the caller.
Limitations¶
DataFrame/Series elements cannot be max/min float/integer. Otherwise SDC and Pandas results are different. Resulting DataFrame/Series has default index and name.
Examples¶
import pandas as pd
from numba import njit
@njit
def series_rolling_cov():
series = pd.Series([3, 3, 3, 5, 8]) # Series of 3, 3, 3, 5, 8
other = pd.Series([3, 4, 4, 4, 8]) # Series of 3, 4, 4, 4, 8
out_series = series.rolling(4).cov(other)
return out_series # Expect series of NaN, NaN, NaN, 0.166667, 4.333333
print(series_rolling_cov())
$ python ./series/rolling/series_rolling_cov.py
0 NaN
1 NaN
2 NaN
3 0.166667
4 4.333333
dtype: float64
import pandas as pd
from numba import njit
@njit
def df_rolling_cov():
df = pd.DataFrame({'A': [3, 3, 3, 5, 8], 'B': [-3, -3, -3, -5, -8]})
other = pd.DataFrame({'A': [3, 4, 4, 4, 8], 'B': [-3, -4, -4, -4, -8]})
out_df = df.rolling(4).cov(other)
# Expect DataFrame of
# {'A': [NaN, NaN, NaN, 0.166667, 4.333333],
# 'B': [NaN, NaN, NaN, 0.166667, 4.333333]}
return out_df
print(df_rolling_cov())
$ python ./dataframe/rolling/dataframe_rolling_cov.py
A B
0 NaN NaN
1 NaN NaN
2 NaN NaN
3 0.166667 0.166667
4 4.333333 4.333333
See also
- Series.rolling
Calling object with a Series.
- DataFrame.rolling
Calling object with a DataFrame.
- Series.cov
Similar method for Series.
- DataFrame.cov
Similar method for DataFrame.