Pandas循环遍历行并跳过行?

问题描述 投票:0回答:1

我有一个pandas数据框,其中一列中的价格和另一列中的日期时间。我要做的就是创建一个回测测试循环,说明价格是否达到某一点,跳过30行并计算该行与第30行之后的价格差异。然后,继续循环到数据帧的最后一行。

有更多的pythonic方式来做这个而不是只进入连续30次?

感谢帮助

样本df:

index                  vol1     vol2          vol3           price  
0            0.0    0.984928    0.842774    0.403604        0.24676   
1            0.0    0.984928    0.842774    0.403604        0.24676   
2            0.0    0.984928    0.842774    0.403604        0.24676   
3            0.0    0.984928    0.842774    0.403604        0.24676   
4            0.0    0.984928    0.842774    0.403604        0.24683   
5            0.0    0.958933    0.843822    0.407730        0.24724   
6            0.0    0.950355    0.842774    0.412017        0.24724   
7            0.0    0.946536    0.843822    0.419604        0.24725   
8            0.0    0.941535    0.843822    0.421247        0.24683   
9            0.0    0.935383    0.842775    0.415184        0.24708   
10           0.0    0.934629    0.842774    0.402836        0.24691 
python pandas loops
1个回答
1
投票

我不确定你想完全跳过这30行之间的行还是想继续。我试着在继续逐行的版本中提出你想要的东西。如Peter所建议的那样,需要样本数据和原型代码,以便更多人可以帮助您。

这是我的示例代码:

# load dataframe to df
df = pd.Dataframe()

# set threshold for the price
limit_price = x

# collect difference of prices as a list
diff_prices = []

# loop through dataframe df
for index, row in df.iterrows():
  # row is pd.Series now, check if it pass certain point here
  if row.prices > limit_price:
    # if pass find the diff of this row and 30 row ahead of it
    # and then add to a list
    diff_prices.append(row.prices - df.iloc[index+30].prices)
  else:
    # if not pass add 0 to a list instead
    diff_prices.append(0)
© www.soinside.com 2019 - 2024. All rights reserved.