![](/img/trans.png)
[英]How can I find at only a certain groups of dates within a sorted list in Python?
[英]How can I find the sum of multiple groups within a series?
我有一系列簡短的〜60個值。 我需要做的是找到系列中24個連續值的最大和。
例如,我將需要能夠找到組[0:23],[1:24],[2:25],[3:26],...,[37:60]的總和組的金額最大。
您可以對serie使用rolling方法: serie.rolling(24).sum()
直接獲取最大max_idx = serie.rolling(24).sum().idxmax()
您的關注范圍是[max_idx-24+1:max_idx]
(從索引max_idx - 24 + 1
到索引max_idx
(均包括索引),因此請小心,如果要檢索這些元素,請使用.loc
應該可以,但如果返回到原始列表,或者如果使用iloc
則必須轉到max_idx + 1
。
由於您的Series
小,您可以使用簡單的dict
理解:
import numpy as np
import pandas as pd
from operator import itemgetter
s = pd.Series(np.random.randint(1, 10, size=60))
result = {f'{i} - {i + 24}': s[i:i + 24].sum() for i in range(len(s) - 24)}
max(result.items(), key=itemgetter(1))[0]
輸出:
'6 - 30'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.