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()
import pandas as pd
import numpy as np
from pandas.api.types import CategoricalDtype

def convert_experience(val):
    if pd.isnull(val):
        return np.nan
    elif val == '>20':
        return 21
    elif val == '<1':
        return 0
    else:
        try:
            return int(val)
        except ValueError:
            return np.nan

def convert_company_size(val):
    sizes = {
        '10/49': 29, '50-99': 74, '100-500': 300,
        '500-999': 750, '1000-4999': 3000,
        '5000-9999': 7500, '10000+': 10000
    }
    return sizes.get(val, np.nan)

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

# --- Step 1: Clean & Convert ---
ds_jobs['experience'] = ds_jobs['experience'].map(convert_experience)
ds_jobs['company_size_num'] = ds_jobs['company_size'].map(convert_company_size)

# Drop rows where these are missing.  Important to do this *before*
#  filtering, so we don't accidentally drop rows that *would* have
#  been included in the filtered set.
ds_jobs = ds_jobs[ds_jobs['experience'].notnull() & ds_jobs['company_size_num'].notnull()]


# --- Step 2: Filter dataset ---
ds_jobs_filtered = ds_jobs[(ds_jobs['experience'] >= 10) & (ds_jobs['company_size_num'] >= 1000)]

# --- Step 3: Type Optimization ---

# Convert 'experience' to ordered category
exp_order_dict = {
    0: '<1', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9',
    10: '10', 11: '11', 12: '12', 13: '13', 14: '14', 15: '15', 16: '16', 17: '17',
    18: '18', 19: '19', 20: '20', 21: '>20'
}
exp_order = list(exp_order_dict.values())
exp_dtype = CategoricalDtype(categories=exp_order, ordered=True)
ds_jobs_filtered['experience'] = ds_jobs_filtered['experience'].map(exp_order_dict).astype(exp_dtype)


# Boolean columns
ds_jobs_filtered['job_change'] = ds_jobs_filtered['job_change'].astype('bool')
ds_jobs_filtered['relevant_experience'] = ds_jobs_filtered['relevant_experience'].map({
    'Has relevant experience': True,
    'No relevant experience': False
}).astype('bool')

# Integer columns
int_cols = ['student_id', 'training_hours']
for col in int_cols:
    ds_jobs_filtered[col] = ds_jobs_filtered[col].astype('int32')

# Float columns
ds_jobs_filtered['city_development_index'] = ds_jobs_filtered['city_development_index'].astype('float16')

# Define the order for the 'company_size' column
company_size_order = ['10/49', '50-99', '100-500', '500-999', '1000-4999', '5000-9999', '10000+']
company_size_dtype = CategoricalDtype(categories=company_size_order, ordered=True)

# Nominal and Ordinal categorical columns
nominal_cols = ['city', 'gender', 'major_discipline', 'company_type']
for col in nominal_cols:
    ds_jobs_filtered[col] = ds_jobs_filtered[col].astype('category')

# Convert 'company_size' to ordered category
ds_jobs_filtered['company_size'] = ds_jobs_filtered['company_size'].astype(company_size_dtype)


# Ordinal categorical: last_new_job
last_job_order = ['never', '1', '2', '3', '4', '>4']
ds_jobs_filtered['last_new_job'] = pd.Categorical(
    ds_jobs_filtered['last_new_job'],
    categories=last_job_order,
    ordered=True
)

# Ordinal categorical: enrolled_university
uni_order = ['no_enrollment', 'Part time course', 'Full time course']
uni_dtype = CategoricalDtype(categories=uni_order, ordered=True)
ds_jobs_filtered['enrolled_university'] = ds_jobs_filtered['enrolled_university'].astype(uni_dtype)

# Ordinal categorical: education_level
edu_order = ['Primary School', 'High School', 'Graduate', 'Masters', 'PhD']
edu_dtype = CategoricalDtype(categories=edu_order, ordered=True)
ds_jobs_filtered['education_level'] = ds_jobs_filtered['education_level'].astype(edu_dtype)

# Final output DataFrame
ds_jobs_transformed = ds_jobs_filtered.drop(columns=['company_size_num'])

# Check memory usage of original and transformed DataFrames
print("Memory usage of original DataFrame:")
print(ds_jobs.info(memory_usage="deep"))
print("\nMemory usage of transformed DataFrame:")
print(ds_jobs_transformed.info(memory_usage="deep"))