簡體   English   中英

Python中時間序列中兩個變量的相關性?

[英]Correlation of Two Variables in a Time Series in Python?

如果我有兩個不同的時間序列數據集,有沒有一種簡單的方法來找到python中兩個集合之間的相關性?

例如:

# [ (dateTimeObject, y, z) ... ]
x = [ (8:00am, 12, 8), (8:10am, 15, 10) .... ]

我如何在Python中獲得y和z的相關性?

這里的吸收速度有點慢。 pandas(http://github.com/wesm/pandas和pandas.sourceforge.net)可能是你最好的選擇。 我有偏見因為我寫了但是:

In [7]: ts1
Out[7]: 
2000-01-03 00:00:00    -0.945653010936
2000-01-04 00:00:00    0.759529904445
2000-01-05 00:00:00    0.177646448683
2000-01-06 00:00:00    0.579750822716
2000-01-07 00:00:00    -0.0752734982291
2000-01-10 00:00:00    0.138730447557
2000-01-11 00:00:00    -0.506961851495

In [8]: ts2
Out[8]: 
2000-01-03 00:00:00    1.10436688823
2000-01-04 00:00:00    0.110075215713
2000-01-05 00:00:00    -0.372818939799
2000-01-06 00:00:00    -0.520443811368
2000-01-07 00:00:00    -0.455928700936
2000-01-10 00:00:00    1.49624355051
2000-01-11 00:00:00    -0.204383054598

In [9]: ts1.corr(ts2)
Out[9]: -0.34768587480980645

值得注意的是,如果您的數據是在不同的日期集上,它將計算成對相關性。 它還會自動排除NaN值!

Scipy有一個具有相關功能的統計模塊。

from scipy import stats
# Y and Z are numpy arrays or lists of variables 
stats.pearsonr(Y, Z)

您可以通過協方差矩陣或相關系數來做到這一點。 http://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.htmlhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html是文檔對於這個功能,前者還附帶了一個如何使用它的示例(corrcoef使用非常相似)。

>>> x = [ (None, 12, 8), (None, 15, 10), (None, 10, 6) ]
>>> data = numpy.array([[e[1] for e in x], [e[2] for e in x]])
>>> numpy.corrcoef(data)
array([[ 1.        ,  0.99339927],
       [ 0.99339927,  1.        ]])

使用numpy:

from numpy import *
v = [ ('k', 1, 2), ('l', 2, 4), ('m', 13, 9) ]
corrcoef([ a[1] for a in v ], [ a[2] for a in v ])[0,1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM