Skip to content

A common problem when creating models to generate business value from data is that the datasets can be so large that it can take days for the model to generate predictions. Ensuring that your dataset is stored as efficiently as possible is crucial for allowing these models to run on a more reasonable timescale without having to reduce the size of the dataset.

You've been hired by a major online data science training provider called Training Data Ltd. to clean up one of their largest customer datasets. This dataset will eventually be used to predict whether their students are looking for a new job or not, information that they will then use to direct them to prospective recruiters.

You've been given access to customer_train.csv, which is a subset of their entire customer dataset, so you can create a proof-of-concept of a much more efficient storage solution. The dataset contains anonymized student information, and whether they were looking for a new job or not during training:

ColumnDescription
student_idA unique ID for each student.
cityA code for the city the student lives in.
city_development_indexA scaled development index for the city.
genderThe student's gender.
relevant_experienceAn indicator of the student's work relevant experience.
enrolled_universityThe type of university course enrolled in (if any).
education_levelThe student's education level.
major_disciplineThe educational discipline of the student.
experienceThe student's total work experience (in years).
company_sizeThe number of employees at the student's current employer.
company_typeThe type of company employing the student.
last_new_jobThe number of years between the student's current and previous jobs.
training_hoursThe number of hours of training completed.
job_changeAn indicator of whether the student is looking for a new job (1) or not (0).
# Import necessary libraries
import pandas as pd

# Load the dataset
ds_jobs = pd.read_csv("customer_train.csv")

# View the dataset
# ds_jobs.head(15)
# Create a copy of ds_jobs for transforming
ds_jobs_transformed = ds_jobs.copy()

# Start coding here. Use as many cells as you like!
len(ds_jobs_transformed)
ds_jobs_transformed.columns
ds_jobs_transformed.info()

Columns containing categories with only two factors must be stored as Booleans (bool).

# Assuming ds_jobs_transformed is already created as a copy from another DataFrame
# Create a dictionary of columns containing ordered categorical data
ordered_cats = {
    'enrolled_university': ['no_enrollment', 'Part time course', 'Full time course'],
    'education_level': ['Primary School', 'High School', 'Graduate', 'Masters', 'Phd'],
    'experience': ['<1'] + list(map(str, range(1, 21))) + ['>20'],
    'company_size': ['<10', '10-49', '50-99', '100-499', '500-999', '1000-4999', '5000-9999', '10000+'],
    'last_new_job': ['never', '1', '2', '3', '4', '>4']
}

# Loop through each column in the DataFrame
for column in ds_jobs_transformed.columns:
    # Check if the column has exactly 2 unique values
    if ds_jobs_transformed[column].nunique() == 2:
        # Convert the column to Boolean
        ds_jobs_transformed[column] = ds_jobs_transformed[column].astype('bool')
    # Check if the column has exactly the int64 format
    elif ds_jobs_transformed[column].dtype == 'int64':
        # Convert the column to int32
        ds_jobs_transformed[column] = ds_jobs_transformed[column].astype('int32')
    # Check if the column's dtype is a float type
    elif pd.api.types.is_float_dtype(ds_jobs_transformed[column]):
        # Convert the column to float16
        ds_jobs_transformed[column] = ds_jobs_transformed[column].astype('float16')
    # This checks if the current column exists as a key in the dictionary ordered_cats.    
    elif column in ordered_cats.keys():
        # This creates a CategoricalDtype object
        # ordered_cats[column] accesses the list of categories associated with the column in ordered_cats. For example, if the column is 'experience', it retrieves ['<1', '1', '2', ...].
        # ordered=True specifies that these categories have a defined order. This is useful for ordinal data (e.g., experience levels, education levels) where the order of categories matters.
        # Example: If column = 'experience', then this line will create a categorical type where the categories are ordered as: category = pd.CategoricalDtype(['<1', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11-20', '>20'], ordered=True)
        category = pd.CategoricalDtype(ordered_cats[column], ordered=True)
        # This line converts the specified column in the DataFrame ds_jobs_transformed to the newly defined ordered categorical type.
        ds_jobs_transformed[column] = ds_jobs_transformed[column].astype(category)
    # Convert remaining columns to standard categories
    else:
        ds_jobs_transformed[column] = ds_jobs_transformed[column].astype('category')   

ds_jobs_transformed.info()
len(ds_jobs_transformed)
# Filter students with 10 or more years experience at companies with at least 1000 employees
ds_jobs_transformed = ds_jobs_transformed[(ds_jobs_transformed['experience'] >= '10') & (ds_jobs_transformed['company_size'] >= '1000-4999')]