當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python pandas.core.window.rolling.Rolling.corr用法及代碼示例

用法:

Rolling.corr(other=None, pairwise=None, ddof=1, **kwargs)

計算滾動相關性。

參數

otherSeries 或 DataFrame,可選

如果未提供,則默認為 self 並產生成對輸出。

pairwise布爾值,默認無

如果為 False,則僅使用 self 和 other 之間的匹配列,並且輸出將是 DataFrame。如果為 True,則將計算所有成對組合,並且在 DataFrame 輸入的情況下,輸出將是 MultiIndexed DataFrame。在缺少元素的情況下,將僅使用完整的成對觀察。

ddof整數,默認 1

Delta 自由度。計算中使用的除數是 N - ddof ,其中 N 表示元素的數量。

**kwargs

為了 NumPy 的兼容性,不會對結果產生影響。

返回

Series或DataFrame

返回類型與 np.float64 dtype 的原始對象相同。

注意

該函數使用 Pearson 的相關性定義 (https://en.wikipedia.org/wiki/Pearson_correlation_coefficient)。

other 未指定時,輸出將為自相關(例如全 1),但 DataFrame 輸入除外,其中 pairwise 設置為 True

函數將為等值序列的相關性返回NaN;這是 0/0 除法錯誤的結果。

pairwise 設置為 False 時,將僅使用 selfother 之間的匹配列。

pairwise 設置為 True 時,輸出將是一個 MultiIndex DataFrame,其中原始索引位於第一級,other DataFrame 列位於第二級。

在缺少元素的情況下,將僅使用完整的成對觀察。

例子

下麵的示例顯示了一個滾動計算,其窗口大小為 4,與使用 numpy.corrcoef() 的等效函數調用匹配。

>>> v1 = [3, 3, 3, 5, 8]
>>> v2 = [3, 4, 4, 4, 8]
>>> # numpy returns a 2X2 array, the correlation coefficient
>>> # is the number at entry [0][1]
>>> print(f"{np.corrcoef(v1[:-1], v2[:-1])[0][1]:.6f}")
0.333333
>>> print(f"{np.corrcoef(v1[1:], v2[1:])[0][1]:.6f}")
0.916949
>>> s1 = pd.Series(v1)
>>> s2 = pd.Series(v2)
>>> s1.rolling(4).corr(s2)
0         NaN
1         NaN
2         NaN
3    0.333333
4    0.916949
dtype:float64

下麵的示例顯示了使用 pairwise 選項對 DataFrame 進行類似的滾動計算。

>>> matrix = np.array([[51., 35.], [49., 30.], [47., 32.],        [46., 31.], [50., 36.]])
>>> print(np.corrcoef(matrix[:-1,0], matrix[:-1,1]).round(7))
[[1.         0.6263001]
 [0.6263001  1.       ]]
>>> print(np.corrcoef(matrix[1:,0], matrix[1:,1]).round(7))
[[1.         0.5553681]
 [0.5553681  1.        ]]
>>> df = pd.DataFrame(matrix, columns=['X','Y'])
>>> df
      X     Y
0  51.0  35.0
1  49.0  30.0
2  47.0  32.0
3  46.0  31.0
4  50.0  36.0
>>> df.rolling(4).corr(pairwise=True)
            X         Y
0 X       NaN       NaN
  Y       NaN       NaN
1 X       NaN       NaN
  Y       NaN       NaN
2 X       NaN       NaN
  Y       NaN       NaN
3 X  1.000000  0.626300
  Y  0.626300  1.000000
4 X  1.000000  0.555368
  Y  0.555368  1.000000

相關用法


注:本文由純淨天空篩選整理自pandas.pydata.org大神的英文原創作品 pandas.core.window.rolling.Rolling.corr。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。