简体   繁体   English

如何在python中附加多个时间序列相关性列表?

[英]how to append more than one list of time series correlation in python?

I want to take correlation between two time series. 我想在两个时间序列之间建立关联。 I used np.correcoef to get the correlations as list. 我使用np.correcoef获取相关性作为列表。 Now I introduced lag suppose 3, how to save 3 different list for 3 different lags. 现在我介绍了滞后假设3,如何为3个不同的滞后保存3个不同的列表。

I tried 我试过了

 for k in range(0,4,1):
      corr_k= [] 
      corr_k.append( np.corrcoef ( T[(365-k):(730-k)] ,T[365:730]) )

I want my result as corr_0 , corr_1, ... for respective lags But I am getting corr_k only. 我希望我的结果分别为corr_0,corr_1 ... ...但是我只得到了corr_k。 I need to make adjacency matrix after this step for each k value. 在此步骤之后,我需要为每个k值制作邻接矩阵。 I am using netCDF file as m data and T is temperature. 我正在使用netCDF文件作为m数据,T是温度。 Any idea how to do that? 任何想法如何做到这一点? thank you. 谢谢。

EDITED WITH MINIMUM EXAMPLE 用最少的示例进行编辑

import numpy as np
T = np.random.rand(100) #defines a dummy T with size 100
corr = {}
for k in range(4):
   corr[k] = np.corrcoef(T[50-k:100-k],T[50:100])

returns a dictionary corr containing arrays. 返回包含数组的字典corr For instance : 例如 :

corr[0]
> array([[1., 1.],
       [1., 1.]])

If this is not applicable to your case, maybe the issue is in the corrcoef , not the "appending" part! 如果这不适用于您的情况,则问题可能出在corrcoef ,而不是“附加”部分!


EDITED WITH DICT 用DICT编辑

When you ask for corr_k in your loop, python has no way of knowing that you want k as a number. 当您在循环中要求corr_k时,python无法知道您希望k为数字。 So it consider that your variable name is corr_k and not corr_0 and so on as you would like. 因此,它认为您的变量名是corr_k而不是corr_0 ,依此类推。 Which is hopeful, think about the nightmare it would be if python changed all k character on its own! 这是充满希望的,想一想噩梦,如果python自己更改了所有k字符! So, to specify a variable name which changes with the loop index, use a dictionary (as in this answer ) and store the lists in it: 因此,要指定随循环索引而变化的变量名,请使用字典(如本答案所示 )并将列表存储在其中:

corr = {}
 for k in range(4):
      corr[k] = np.corrcoef ( T[(365-k):(730-k)] ,T[365:730] ) 

Then you will have your outputs with: corr[0] , corr[1] , corr[2] , corr[3] . 然后,您将获得以下输出: corr[0]corr[1]corr[2]corr[3]


It is difficult to test your code as we do not have T here, but as a first insight I see that for each step your are defining again corr_k=[] , hence overwriting your list rather than appending it. 由于这里没有T ,因此很难测试您的代码,但是作为第一步,我发现对于每个步骤,您都在定义corr_k=[] ,因此覆盖了列表而不是附加列表。 Try: 尝试:

corr_k= [] 
for k in range(4):
      corr_k.append( np.corrcoef ( T[(365-k):(730-k)] ,T[365:730]) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM