我正在尝试使用条件语句遍历数据框。
我尝试拆分循环,它们都单独工作;但是,组合后,循环将在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
答案 0 :(得分:0)
因为您在for
循环之外打印i,所以不会得到数字列表,而只会得到i
的最后一个值
也可能是复制/粘贴错误,但是您在stock = round((cash/df2.iloc[i][3])-0.5)
之前缩进了很多。
您能举个例子说明数据框中的内容吗?
答案 1 :(得分:0)
似乎您在df2
行上使用循环,但是在循环中的任何地方都没有使用index
和row
。
如果您要遍历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)