【问题标题】:Python pandas grouping for correlation analysis用于相关分析的 Python pandas 分组
【发布时间】:2015-01-17 09:57:35
【问题描述】:

假设有两个数据框,每个都有一个日期时间索引,每个都有一列未命名的数据。数据帧的长度不同,日期时间索引可能重叠也可能不重叠。

df1 长度为 20。df2 长度为 400。数据列由随机浮点数组成。

我想通过 df2 进行迭代,每次迭代需要 20 个单位,每次迭代将起始向量增加一个单位 - 类似地,结束向量增加一个单位。在每次迭代中,我想计算 df1 的 20 个单位和我为 df2 的这次迭代选择的 20 个单位之间的相关性。然后将记录该相关系数和其他统计数据。

一旦循环完成,我想用 df2 的 20 单位向量绘制 df1,满足我的统计搜索 - 因此需要跟上某种程度的索引,以便在分析完成后重新获取向量。

有什么想法吗?

【问题讨论】:

    标签: python pandas correlation


    【解决方案1】:

    在不了解问题的更多细节(例如,您为什么要这样做或日期很重要)的情况下,这将满足您的要求。我很高兴根据您的反馈进行更新。

    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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多