首页 > 解决方案 > 数据帧循环停止

问题描述

我正在尝试使用条件语句遍历数据框。

我曾尝试拆分循环,它们都单独工作;但是,当组合时,循环会在 1 次迭代后停止。

i=0 
stock = 100
cash = 0

for index, row in df2.iterrows(): 
    if df2.iloc[i][3] > df2.iloc[i+1][3]:          
        if stock == 0:                             #future stock is cheaper, but no stock to sell
           continue 
        else:
            cash = cash + df2.iloc[i][3] * stock   #future stock is cheaper, so sell
            stock = 0 
    else:                                          #future stock is more expensive, so buy 
        stock = round((cash/df2.iloc[i][3])-0.5) 
       cash = round((cash - stock*df2.iloc[i][3])-0.5)
    i+=1
i

打印 i 当它应该给出一个数字列表时只给出 1(即循环在一次迭代后停止)

标签: pythonpandasdataframe

解决方案


似乎您正在对df2行使用循环,但您没有在循环中的任何地方使用您的indexrow。如果您尝试遍历您的每一行,df2那么我建议:

i=0 
stock = 100
cash = 0

for i in range(df2.shape[0]-1): # iterate over all rows except last iloc[i+1] is the last
    if df2.iloc[i][3] > df2.iloc[i+1][3]:          
        if stock == 0:                             #future stock is cheaper, but   no stock to sell
           continue 
        else:
            cash = cash + df2.iloc[i][3] * stock   #future stock is cheaper, so sell 
            stock = 0 
    else:                                          #future stock is more expensive, so buy 
        stock = round((cash/df2.iloc[i][3])-0.5) 
        cash = round((cash - stock*df2.iloc[i][3])-0.5)
print(i)

推荐阅读