Pandas在一排排的循环和跳跃?

2024-09-28 19:30:03 发布

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

我有一个pandas数据框,其中一列是价格,另一列是datetime。我所要做的就是创建一个回溯测试循环,如果价格达到某一点,跳过30行,然后计算该行与之后第30行之间的价格差异。然后,继续循环到数据帧的最后一行。在

有没有一种更像Python的方法来完成这项任务,而不是仅仅输入continue 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 

Tags: 数据方法pandasdfdatetimeindex样品价格
1条回答
网友
1楼 · 发布于 2024-09-28 19:30:03

我不确定你是想完全跳过这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)

相关问题 更多 >