2015-01-15 36 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')