我试图在 for 循环中使用两个条目,并让它们在每次迭代中移动。
我的列表看起来像这样:change_loc = [0, 380, 499, 1742, 1862, 2938]
,它是在以下函数的第一行计算的:
def average_points(sal_data):
"""Find the changing indexes then average 5 last and first points."""
data = copy.deepcopy(sal_data)
start = 0
end = data.index[-1]
change_loc.insert(0, start)
change_loc.append(end)
for change in change_loc:
first = (data['sal'][0:380].iloc[-5:])
last= data['sal'][380:499].iloc[:5]
mean = first.append(last).mean()
return pd.Series({
"average_points": mean
})
在函数中,我希望 for 循环从两个点移动到下两个点。例如,目前该函数使用 [0:380]
和 [380:499]
。接下来我希望它使用 [380:499]
和 [499:1782]
等。知道怎么做吗?我需要柜台吗?
这个函数的目标是抓取一段数据的最后5个和前5个条目,然后抓取这10个点的平均值。
谢谢!
答案 0 :(得分:0)
查看此代码:
change_loc = [1,2,3,4,5,6,7]
for i in range(1, len(change_loc) -1):
first = [change_loc[i-1], change_loc[i]]
last = [change_loc[i], change_loc[i+1]]
print('loop {}: {}, {}'.format(i, first, last))
结果:
loop 1: [1, 2], [2, 3]
loop 2: [2, 3], [3, 4]
loop 3: [3, 4], [4, 5]
loop 4: [4, 5], [5, 6]
loop 5: [5, 6], [6, 7]