Skip to main content

analyze_synthetic_sales.py

Download source

analyze_synthetic_sales.py
import pandas as pd


# 1. Load synthetic_sales_timeseries.csv into a DataFrame named sales.
# After reading the file, convert the date column to datetime with:
# sales["date"] = pd.to_datetime(sales["date"])
# Display the first five rows.


# 2. Explore the DataFrame.
# Display its number of rows and columns, its column names, and its data types.


# 3. Explore rows and columns with iloc and loc.
# Use iloc to display rows 0 to 4 and columns at positions 0,
# 2, and 3. Use loc to display rows with labels 0 to 4 and columns date,
# product, and turnover.


# 4. Group the data by region and calculate the total turnover for each region.


# 5. Create a pivot table with regions as rows, products as columns, and the
# summed turnover as the values.


# 6. Select the North region's Laptop observations into a new DataFrame named
# time_series. Keep only the date and turnover columns, sort the observations
# by date, and display its first few rows and shape.


# 7. Calculate a ten-observation moving average using a for loop.
# Add a column named MA10_loop. Leave the first nine values empty, and store
# each average alongside the last observation in its ten-row window. The first
# nine rows have no complete ten-observation window.
# Check that the first moving average equals the mean of the first ten turnover
# values.


# 8. Create a new Python script and copy the solution for task 7. Extract the loop
# calculation into a function name calculate_moving_average. The function should 
# take a DataFrame and window size, and return a Series of moving averages for the 
# turnover column. The function overwrites the MA10_loop column when it stores its results.
# Making the window size flexible is an advanced task beyond the exam materials.
# Use the function to add a column named MA10_function. Display the first 15
# values of both moving-average columns.


# 9. Create a new column named above_MA10 to mark observations where
# turnover is above its corresponding moving average.
# Create another column named two_above_MA10 to mark observations
# where turnover has been above its moving average for two consecutive
# observations (the current observation and the preceding one).
# Use True and False to mark the observations.


# 10. Finish by plotting turnover and MA10_function together as a line chart.
# Use date on the x-axis. Pandas chooses date ticks automatically; rotate the
# tick labels with rot=45 so they remain readable.