Merging months into quarters
Now we saw what to do when we wanted to split quarters into months for more detailed monthly information. But what happens when the opposite is true and we wish to combine data into fewer columns? This is typical when dealing with historical data, when monthly details may not be necessary, or when we need a highly consolidated version of the data for a report.
The key here is to create an index, and then only add to the quarter total quarter
in cycles of 3, or until the length of the list. We can do this with the following code:
if index % 3 == 0 or index == len(months):
This code checks whether the index divided by three yields a remainder of 0, or if the index is at the end of the list months
. Thus, in a loop it will execute the specified code every three months or when it reaches the end of the list.
The monthly sales are already provided in the code as months
, containing the sales from the first two quarters, as well as the first month of Q3. Your task is to generate a new list called quarters
that contains the quarterly totals from the first three months (which includes the partial total of Q3).
Cet exercice fait partie du cours
Financial Forecasting in Python
Instructions
Initialize an empty list
quarters
to contain the new quarterly values, and an index variableindex
set to1
.Create a for loop to find the monthly
sales
inmonths
:- Add the monthly sales to
quarter
. - If it's the end of the quarter or the end of the list
months
, append your quarterly total toquarters
. - Reset the quarterly total
quarter
to 0, increment the index by 1 (this has been done for you).
- Add the monthly sales to
Print the quarterly totals.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# 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], ____, ____))