列表索引超出范围Python/Pandas

2024-06-28 15:17:14 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我正在编写这个python代码,使用pandas分析一些股票数据。我用两个too循环来累积利润。但是它给了我列表索引超出范围的错误。有人能帮忙吗?df是我使用的数据帧,它有大约10列,包括'invest'和'percentchange'。df['invest']列都是二进制数1或0,df['percentchange']是股价与上一天相比的变化。这里的windows意味着如果我看到windows连续0,比如2个连续0,我会在第二天买入并卖出。在

这是我的任务。这不是真正的股票分析。所以请不要把分析方法看得太重。这些只是为了演示python的数据科学

count=0
countseq=0
principal=100
windows=[1,2,3,4,5]
profit_loss=[0,0,0,0,0]
for i in windows:
    for j in range(len(df)-1):
        if df['invest'][j]==0:
            count+=1
            if count==i:
                profit_loss[i]+=principal*df['percent change'][j+1]
                count=0 
                countseq+=1


IndexError                                Traceback (most recent call last)
<ipython-input-119-53972da7243a> in <module>()
     10             count+=1
     11             if count==i:
---> 12                 profit_loss[i]+=principal*df['percent change'][j+1]
     13                 count=0
     14                 countseq+=1

IndexError: list index out of range

Tags: 数据inprincipaldfforifwindowscount