OA. free
Free
Exl Core Cs & Systems Data Science Medium

What is the output of the following Python code?

Exl technical mcq question, verified with a worked answer. Free to practise - no sign-up.

What is the output of the following Python code?

import pandas as pd

df = pd.DataFrame({
    'Date': pd.date_range('2023-02-01', '2023-02-28'),
    'Value': list(range(1, 29))
})

grouped = df.groupby(pd.Grouper(key='Date', freq='W'))
result = grouped.apply(lambda x: x['Value'].sum()).resample('M').mean()
print(result)
Choose one option.
Show answer & explanation
Answer: A. 2023-02-28 87.75, 2023-03-31 55.00

The code groups daily data into weekly sums, then resamples those weekly sums into monthly means. Because the weekly bins end on Sundays, the final week of February spills into March, creating two monthly entries (February and March) with the average of the weekly sums falling into each.

Step-by-step Derivation:
Step 1: Create DataFrame. 'Date' ranges from 2023-02-01 to 2023-02-28. 'Value' is 1 to 28.
Step 2: Group by 'W' (Weekly, ending Sunday).

  • Week 1: Feb 1 (Wed) to Feb 5 (Sun). Values: 1, 2, 3, 4, 5. Sum = 15. Label: 2023-02-05.
  • Week 2: Feb 6 (Mon) to Feb 12 (Sun). Values: 6 to 12. Sum = (6+12)*7/2 = 63. Label: 2023-02-12.
  • Week 3: Feb 13 (Mon) to Feb 19 (Sun). Values: 13 to 19. Sum = (13+19)*7/2 = 112. Label: 2023-02-19.
  • Week 4: Feb 20 (Mon) to Feb 26 (Sun). Values: 20 to 26. Sum = (20+26)*7/2 = 161. Label: 2023-02-26.
  • Week 5: Feb 27 (Mon) to Feb 28 (Tue). Values: 27, 28. Sum = 55. Label: 2023-03-05.
    Step 3: Resample by 'M' (Month End) and calculate mean.
  • February group (Labels 02-05, 02-12, 02-19, 02-26): Mean = (15 + 63 + 112 + 161) / 4 = 351 / 4 = 87.75. Label: 2023-02-28.
  • March group (Label 03-05): Mean = 55 / 1 = 55.00. Label: 2023-03-31.
    Step 4: Final result is a Series with indices 2023-02-28 (87.75) and 2023-03-31 (55.00).