pandas 嵌套循环超出列表范围

pandas nested loops out of range of list

我从一个名为 returnlist 的列表开始:

len(returnlist)
9
returnlist[0]

    AAPL    AMZN    BAC GE  GM  GOOG    GS  SNP XOM
Date                                    
2012-01-09  60.247143   178.559998  6.27    18.860001   22.840000   309.218842  94.690002   89.053848   85.500000
2012-01-10  60.462856   179.339996  6.63    18.719999   23.240000   309.556641  98.330002   89.430771   85.720001
2012-01-11  60.364285   178.899994  6.87    18.879999   24.469999   310.957520  99.760002   88.984619   85.080002
2012-01-12  60.198570   175.929993  6.79    18.930000   24.670000   312.785645  101.209999  87.838463   84.739998
2012-01-13  59.972858   178.419998  6.61    18.840000   24.290001   310.475647  98.959999   87.792313   84.879997

我想得到每天的腿returns然后用cumsum得到累积的returns。

weeklyreturns=[]
for i in range (1,10):
    returns=pd.DataFrame()
    for stock in returnlist[i]:
        if stock not in returnlist[i]:
            returns[stock]=np.log(returnlist[i][stock]).diff()
    weeklyreturns.append(returns)

我得到的错误是:

----> 4     for stock in returnlist[i]:
      5         if stock not in returnlist[i]:
      6             returns[stock]=np.log(returnlist[i][stock]).diff()

IndexError: list index out of range

因为 len(returnlist) == 9,这意味着 returnlist 的最后一项是 returnlist[8]

当您遍历 range(1,10) 时,您将从 returnlist[1] 开始并最终到达 returnlist[9],它不存在。

看来你真正需要的是遍历[=​​16=].