Skip to content

Walmart is the biggest retail store in the United States. Just like others, they have been expanding their e-commerce part of the business. By the end of 2022, e-commerce represented a roaring $80 billion in sales, which is 13% of total sales of Walmart. One of the main factors that affects their sales is public holidays, like the Super Bowl, Labour Day, Thanksgiving, and Christmas.

In this project, you have been tasked with creating a data pipeline for the analysis of supply and demand around the holidays, along with conducting a preliminary analysis of the data. You will be working with two data sources: grocery sales and complementary data. You have been provided with the grocery_sales table in PostgreSQL database with the following features:

grocery_sales

  • "index" - unique ID of the row
  • "Store_ID" - the store number
  • "Date" - the week of sales
  • "Weekly_Sales" - sales for the given store

Also, you have the extra_data.parquet file that contains complementary data:

extra_data.parquet

  • "IsHoliday" - Whether the week contains a public holiday - 1 if yes, 0 if no.
  • "Temperature" - Temperature on the day of sale
  • "Fuel_Price" - Cost of fuel in the region
  • "CPI" – Prevailing consumer price index
  • "Unemployment" - The prevailing unemployment rate
  • "MarkDown1", "MarkDown2", "MarkDown3", "MarkDown4" - number of promotional markdowns
  • "Dept" - Department Number in each store
  • "Size" - size of the store
  • "Type" - type of the store (depends on Size column)

You will need to merge those files and perform some data manipulations. The transformed DataFrame can then be stored as the clean_data variable containing the following columns:

  • "Store_ID"
  • "Month"
  • "Dept"
  • "IsHoliday"
  • "Weekly_Sales"
  • "CPI"
  • ""Unemployment""

After merging and cleaning the data, you will have to analyze monthly sales of Walmart and store the results of your analysis as the agg_data variable that should look like:

MonthWeekly_Sales
1.033174.178494
2.034333.326579
......

Finally, you should save the clean_data and agg_data as the csv files.

It is recommended to use pandas for this project.

Spinner
DataFrameas
grocery_sales
variable
-- Query all the data from grocery_sales table
SELECT *
FROM grocery_sales;
import pandas as pd
import os

def extract(sql_df, parquet_path):
    """
    Extracts data from a SQL DataFrame and a Parquet file.

    Args:
        sql_df (pd.DataFrame): SQL DataFrame.
        parquet_path (str): Path to the Parquet file.

    Returns:
        pd.DataFrame: Merged DataFrame.
    """

    parquet_df = pd.read_parquet(parquet_path)
    merged_df = sql_df.merge(parquet_df, on='index')
    return merged_df

def transform(raw_data):
    """
    Transforms raw data by filling missing values, formatting dates,
    creating a new column, filtering rows, and dropping unnecessary columns.

    Args:
        raw_data (pd.DataFrame): Raw data DataFrame.

    Returns:
        pd.DataFrame: Cleaned data DataFrame.
    """

    raw_data.fillna(
        {
            "CPI": raw_data["CPI"].mean(),
            "Weekly_Sales": raw_data["Weekly_Sales"].mean(),
            "Unemployment": raw_data["Unemployment"].mean()
        },
        inplace=True
    )

    raw_data["Date"] = pd.to_datetime(raw_data["Date"], format="%Y-%m-%d")
    raw_data["Month"] = raw_data["Date"].dt.month
    raw_data = raw_data[raw_data["Weekly_Sales"] > 10_000]
    raw_data = raw_data.drop(columns=["index", "Date", "Temperature", "Fuel_Price", "MarkDown1", "MarkDown2", "MarkDown3", "MarkDown4", "MarkDown5", "Type", "Size"], axis=0)

    return raw_data

def avg_monthly_sales(df):
    """
    Calculates average monthly sales.

    Args:
        df (pd.DataFrame): DataFrame containing data.

    Returns:
        pd.Series: Series with average monthly sales.
    """

    df = df.groupby("Month")["Weekly_Sales"].mean().round(2)
    df = df.rename("Avg_Sales")
    df = df.reset_index()
    return df

def load(cleaned_df, clean_df_path, agg_df, agg_df_path):
    """
    Saves cleaned and aggregated data to CSV files.

    Args:
        cleaned_df (pd.DataFrame): Cleaned DataFrame.
        clean_df_path (str): Path to save cleaned DataFrame.
        agg_df (pd.Series): Aggregated DataFrame.
        agg_df_path (str): Path to save aggregated DataFrame.
    """

    cleaned_df.to_csv(clean_df_path, index=False)
    agg_df.to_csv(agg_df_path, index=False)

def validation(file_path):
    """
    Validates if a file exists.

    Args:
        file_path (str): Path to the file.

    Returns:
        bool: True if the file exists, False otherwise.
    """

    if os.path.exists(file_path):
        print(f"The {file_path} exists")
        return True
    else:
        raise Exception(f"There is no file in the {file_path}")

# Main execution
merged_df = extract(grocery_sales, 'extra_data.parquet')
clean_data = transform(merged_df)
agg_data = avg_monthly_sales(clean_data)
load(clean_data, "./clean_data.csv", agg_data, "./agg_data.csv")

print(validation("clean_data.csv"))
print(validation("agg_data.csv"))