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")

print(ds_jobs.shape)

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

# Start coding here. Use as many cells as you like!
# look at the column info and memory usage before transforming
ds_jobs_transformed.info()

Converting into desired dtypes

def convert_cols_to_type(df, cols, desired_type):
    """
    Converts a list of columns into desired dtype on df
    """
    for col in cols:
        df[col] = df[col].astype(desired_type)
        
    return df

# binary columns
binary_cols = [col for col in ds_jobs_transformed.columns if ds_jobs_transformed[col].nunique() == 2]
# convert binary columns
ds_jobs_transformed = convert_cols_to_type(ds_jobs_transformed, binary_cols, bool)

# convert int64 to int32 
int_cols = [col for col in ds_jobs_transformed.columns if ds_jobs_transformed[col].dtype == int]
ds_jobs_transformed = convert_cols_to_type(ds_jobs_transformed, int_cols, 'int32')

# convert float64 to 16-bit floats
float_cols = [col for col in ds_jobs_transformed.columns if ds_jobs_transformed[col].dtype == float]
ds_jobs_transformed = convert_cols_to_type(ds_jobs_transformed, float_cols, 'float16')

Converting nominal and ordinal categories into category types

nominal_vars = ['city', 'gender', 'major_discipline', 'company_type']

# convert nominal vars into category type
ds_jobs_transformed = convert_cols_to_type(ds_jobs_transformed, nominal_vars, 'category')
# creating ordered categories for ordinal vars
ordinal_dict = {
    'education_level' : ["Primary School", "High School", "Graduate", "Masters", "Phd"],
    'company_size' : ['<10', '10-49', '50-99', '100-499', '500-999', '1000-4999', '5000-9999', '10000+'],
    'experience' : [],
    'last_new_job' : ['never', '1', '2', '3', '4', '>5'],
    'enrolled_university' : ['no_enrollment', 'Part time course', 'Full time course']
}

# creating experience order list
experience_order = [str(i) for i in range(0, 21)]
experience_order.append('>20')
ordinal_dict['experience'] = experience_order

# filing missing values in experience with 0
ds_jobs_transformed['experience'].fillna('0', inplace=True)

# Converting the ordinal categories now
for col, order in ordinal_dict.items():
    ds_jobs_transformed[col] = pd.Categorical(ds_jobs_transformed[col], categories = order, ordered = True)

Filtering the dataframe

We want the final transformed dataframe to contain students with 10 or more years of experience at companies with at least 1000 employes

We can accomplish this by boolean indexing

# filtering the dataframe to contain students with 10 or more years of 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')]

ds_jobs_transformed
# final shape comparison

print(f"The shape of ds_jobs: {ds_jobs.shape}")
print(f"The shape of transformed ds_jobs: {ds_jobs_transformed.shape}")

print(f"The final transformed is {ds_jobs_transformed.shape[0] * 100 / ds_jobs.shape[0]:.2f}% of the original df")

ds_jobs_transformed.info()

We can see we went from 2+ megabytes into 134 KB!