pandas.core.groupby.DataFrameGroupBy.cov#
- DataFrameGroupBy.cov(min_periods=None, ddof=1, numeric_only=False)[源代码]#
计算列的成对协方差,排除 NA/null 值。
Compute the pairwise covariance among the series of a DataFrame. The returned data frame is the covariance matrix of the columns of the DataFrame.
NA和null值都会被自动排除在计算之外。(有关缺失值偏差的说明,请参见下文。)可以为每个生成的值设置最小观测值的阈值。低于此阈值的观测值比较将返回``NaN``。
此方法通常用于时间序列数据的分析,以了解不同度量值随时间的相互关系。
- Parameters:
- min_periodsint, optional
每对列所需的最小观测值数量,以便得到有效结果。
- ddofint, 默认值 1
Delta自由度。计算中使用的除数是``N - ddof``,其中``N``表示元素的数量。此参数仅在DataFrame中没有``nan``时适用。
- numeric_onlybool,默认 False
仅包含 float, int 或 boolean 数据。
在 1.5.0 版本加入.
在 2.0.0 版本发生变更:
numeric_only的默认值现在是False。
- Returns:
- DataFrame
DataFrame序列的协方差矩阵。
参见
Series.cov计算与另一个Series的协方差。
core.window.ewm.ExponentialMovingWindow.cov指数加权样本协方差。
core.window.expanding.Expanding.cov展开样本协方差。
core.window.rolling.Rolling.cov滚动样本协方差。
Notes
返回DataFrame时间序列的协方差矩阵。协方差按N-ddof归一化。
For DataFrames that have Series that are missing data (assuming that data is missing at random) the returned covariance matrix will be an unbiased estimate of the variance and covariance between the member Series.
However, for many applications this estimate may not be acceptable because the estimate covariance matrix is not guaranteed to be positive semi-definite. This could lead to estimate correlations having absolute values which are greater than one, and/or a non-invertible covariance matrix. See Estimation of covariance matrices for more details.
Examples
>>> df = pd.DataFrame([(1, 2), (0, 3), (2, 0), (1, 1)], ... columns=['dogs', 'cats']) >>> df.cov() dogs cats dogs 0.666667 -1.000000 cats -1.000000 1.666667
>>> np.random.seed(42) >>> df = pd.DataFrame(np.random.randn(1000, 5), ... columns=['a', 'b', 'c', 'd', 'e']) >>> df.cov() a b c d e a 0.998438 -0.020161 0.059277 -0.008943 0.014144 b -0.020161 1.059352 -0.008543 -0.024738 0.009826 c 0.059277 -0.008543 1.010670 -0.001486 -0.000271 d -0.008943 -0.024738 -0.001486 0.921297 -0.013692 e 0.014144 0.009826 -0.000271 -0.013692 0.977795
最小周期数
此方法还支持一个可选的
min_periods关键字参数,该参数指定每列对需要的最少非NA观测值数量,以获得有效结果:>>> np.random.seed(42) >>> df = pd.DataFrame(np.random.randn(20, 3), ... columns=['a', 'b', 'c']) >>> df.loc[df.index[:5], 'a'] = np.nan >>> df.loc[df.index[5:10], 'b'] = np.nan >>> df.cov(min_periods=12) a b c a 0.316741 NaN -0.150812 b NaN 1.248003 0.191417 c -0.150812 0.191417 0.895202