Skip to content

You've recently started a new position as a Data Engineer at an energy company. Previously, analysts on other teams had to manually retrieve and clean data every quarter to understand changes in the sales and capability of different energy types. This process normally took days and was something that most analytsts dreaded. Your job is to automate this process by building a data pipeline. You'll write this data pipeline to pull data each month, helping to provide more rapid insights and free up time for your data consumers.

You will achieve this using the pandas library and its powerful parsing features. You'll be working with two raw files; electricity_sales.csv and electricity_capability_nested.json.

Below, you'll find a data dictionary for the electricity_sales.csv dataset, which you'll be transforming in just a bit. Good luck!

FieldData Type
periodstr
stateidstr
stateDescriptionstr
sectoridstr
sectorNamestr
pricefloat
price-unitsstr
import pandas as pd
import json 
import os
def extract_tabular_data(file_path: str):
    """Extract data from a tabular file_format, with pandas.""" 
    _, file_extension = os.path.splitext(file_path) 
    file_extension = file_extension.lower() 

    if file_extension == '.csv': 
        try: 
            df = pd.read_csv(file_path)
            return df 
        except FileNotFoundError:
            print(f"Error: The file '{file_path}' was not found")
            raise 
        except Exception as e: 
            print(f"error reading CSV file '{file_path}': {e}")
            raise 
    elif file_extension == '.parquet': 
        try: 
            df = pd.read_parquet(file_path)
            return df 
        except FileNotFoundError:
            print(f"Error: The file '{file_path}' was not found")
            raise 
        except Exception as e: 
            print(f"error reading Parquet file '{file_path}': {e}")
            raise 
    else: 
        error_message = "Warning: Invalid file extension. Please try with .csv or .parquet!"
        print(error_message)
        raise ValueError(error_message) 
# Pass file to function 
tabular_data = extract_tabular_data('electricity_sales.csv') 

print(tabular_data.head())
def extract_json_data(file_path):
    with open(file_path, 'r') as file:
        js_data = json.load(file)
    js_df = pd.json_normalize(js_data)
    return js_df
# Pass func 1 
raw_electricity_capability_df = extract_json_data("electricity_capability_nested.json") 
raw_electricity_capability_df.head()
def transform_electricity_sales_data(raw_data: pd.DataFrame):
    """
    Transform electricity sales to find the total amount of electricity sold
    in the residential and transportation sectors.
    
    To transform the electricity sales data, you'll need to do the following:
    - Drop any records with NA values in the `price` column. Do this inplace.
    - Only keep records with a `sectorName` of "residential" or "transportation".
    - Create a `month` column using the first 4 characters of the values in `period`.
    - Create a `year` column using the last 2 characters of the values in `period`.
    - Return the transformed `DataFrame`, keeping only the columns `year`, `month`, `stateid`, `price` and `price-units`.
    """ 
    transformed_df = raw_data.dropna(subset=['price']) 
    transformed_df = transformed_df.loc[transformed_df['sectorName'].isin(['residential', 'transportation'])] 
    transformed_df['month'] = transformed_df['period'].str[0:4] 
    transformed_df['year'] = transformed_df['period'].str[-2:]
    transformed_df = transformed_df[['year', 'month', 'stateid', 'price', 'price-units']] 
    return transformed_df
    
    
tr_electricity_sales_df = transform_electricity_sales_data(tabular_data)
tr_electricity_sales_df.head()
def load(dataframe: pd.DataFrame, file_path: str):
    """Load a DataFrame to a file in either CSV or Parquet format.""" 
    _, file_extension = os.path.splitext(file_path) 
    file_extension = file_extension.lower()
    
    if file_extension == '.csv': 
        try: 
            dataframe.to_csv(file_path) 
            return file_path  
        except Exception as e: 
            print(f"error loading dataframe to CSV file '{file_path}': {e}")
            raise 
    elif file_extension == '.parquet': 
        try: 
            dataframe.to_parquet(file_path) 
            return file_path 
        except Exception as e: 
            print(f"error loading dataframe to Parquet file '{file_path}': {e}")
            raise 
    else: 
        error_message = "Warning: {filepath} is not a valid file type. Please try again!_"
        print(error_message)
        raise ValueError(error_message) 
    
    
# Ready for the moment of truth? It's time to test the functions that you wrote!
raw_electricity_capability_df = extract_json_data("electricity_capability_nested.json")
raw_electricity_sales_df = extract_tabular_data("electricity_sales.csv")

cleaned_electricity_sales_df = transform_electricity_sales_data(raw_electricity_sales_df)

load(raw_electricity_capability_df, "loaded__electricity_capability.parquet")
load(cleaned_electricity_sales_df, "loaded__electricity_sales.csv")