2015-01-15 40 views
0

假設兩個數據幀,每個數據幀都帶有日期時間索引,並且每個數據幀都有一列未命名的數據。數據幀長度不同,日期時間索引可能重疊也可能不重疊。用於相關分析的Python熊貓分組

df1是長度20. df2是長度400.數據列由隨機浮點數組成。

我想通過df2迭代每次迭代需要20個單元,每次迭代將開始向量增加一個單位 - 類似地,結束向量增加一個單位。在每次迭代中,我想計算df1的20個單位與我爲df2的這個迭代選擇的20個單位之間的相關性。然後記錄該相關係數和其他統計數據。

一旦循環完成,我想用滿足我的統計搜索的df2的20個單位矢量繪製df1 - 因此需要跟上一定程度的索引以在分析完成後重新獲取矢量。

有什麼想法?

回答

0

不知道更多具體的問題,例如,爲什麼你這樣做或做日期很重要,這將做你所問。我很樂意根據您的反饋進行更新。

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import random 

df1 = pd.DataFrame({'a':[random.randint(0, 20) for x in range(20)]}, index = pd.date_range(start = '2013-01-01',periods = 20, freq = 'D')) 
df2 = pd.DataFrame({'b':[random.randint(0, 20) for x in range(400)]}, index = pd.date_range(start = '2013-01-10',periods = 400, freq = 'D')) 

corr = pd.DataFrame() 
for i in range(0,380): 

    t0 = df1.reset_index()['a'] # grab the numbers from df1 
    t1 = df2.iloc[i:i+20].reset_index()['b'] # grab 20 days, incrementing by one each time 
    t2 = df2.iloc[i:i+20].index[0] # set the index to be the first day of df2 

    corr = corr.append(pd.DataFrame({'corr':t0.corr(t1)}, index = [t2])) #calculate the correlation and append it to the DF 

# plot it and save the graph 
corr.plot() 
plt.title("Correlation Graph") 
plt.ylabel("(%)") 
plt.grid(True) 
plt.show() 
plt.savefig('corr.png')