將月份彙總成季度
先前我們示範了如何把季度拆成月份,以取得更細的月度資訊。那相反的情況呢?如果要把資料合併成更少的欄位該怎麼做?這在處理歷史資料時很常見,因為可能不需要逐月細節,或是報表需要高度彙整的版本。
關鍵是在建立一個索引,然後只在每 3 的循環中,或直到清單長度為止,才把金額加到季度小計 quarter。可以用下面這行程式碼達成:
if index % 3 == 0 or index == len(months):
這段程式會檢查索引除以 3 是否得到餘數 0,或索引是否已到清單 months 的最後。因此,放在迴圈中時,它會每三個月或到達清單末端時執行指定的程式碼。
月銷售額已在程式中以 months 提供,包含前兩個季度以及第 3 季的第一個月。你的任務是產生一個新清單 quarters,其中包含前三個月的季度總額(包含第 3 季的部分累計)。
本練習屬於課程
使用 Python 進行財務預測
練習說明
初始化一個空清單
quarters來存放新的季度值,並將索引變數index設為1。建立一個 for 迴圈,逐一取得
months中每月的sales:- 將當月銷售額加到
quarter。 - 若到達季度末或清單
months的末端,將季度小計加到quarters。 - 將季度小計
quarter重設為 0,索引加 1(這一步已替你完成)。
- 將當月銷售額加到
列印季度總額。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a months list, as well as an index, and set the quarter to 0
months = [100, 100, 150, 250, 300, 10, 20]
quarter = 0
____ = ____
____ = ____
# Create for loop for quarter, print result, and increment the index
for sales in months:
quarter += ____
if index % ____ == ____ or index == len(____):
____.append(____)
quarter = 0
index = index + 1
print("The quarter totals are Q1: {}, Q2: {}, Q3: {}".format(quarters[0], ____, ____))