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 required libraries
import pandas as pd

# Load and duplicate the dataset
ds_jobs = pd.read_csv("customer_train.csv")
ds_jobs_transformed = ds_jobs.copy()

# Perform exploratory data analysis to categorize columns
for column in ds_jobs.select_dtypes(include='object').columns:
    print(ds_jobs_transformed[column].value_counts(), '\n')

# Define ordered categorical columns
ordered_cats = {
    'enrolled_university': ['no_enrollment', 'Part time course', 'Full time course'],
    'education_level': ['Primary School', 'High School', 'Graduate', 'Masters', 'Phd'],
    'experience': ['<1'] + [str(year) for year in 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']
}

# Define mapping for two-factor categorical columns
two_factor_cats = {
    'relevant_experience': {'No relevant experience': False, 'Has relevant experience': True},
    'job_change': {0.0: False, 1.0: True}
}

# Iterate over DataFrame columns to change data types
for column in ds_jobs_transformed:
    
    # Map two-factor categories to Boolean values
    if column in ['relevant_experience', 'job_change']:
        ds_jobs_transformed[column] = ds_jobs_transformed[column].map(two_factor_cats[column])
    
    # Convert specific integer columns to int32
    elif column in ['student_id', 'training_hours']:
        ds_jobs_transformed[column] = ds_jobs_transformed[column].astype('int32')
    
    # Convert float column to float16
    elif column == 'city_development_index':
        ds_jobs_transformed[column] = ds_jobs_transformed[column].astype('float16')
    
    # Convert columns with ordered categories
    elif column in ordered_cats:
        cat_type = pd.CategoricalDtype(categories=ordered_cats[column], ordered=True)
        ds_jobs_transformed[column] = ds_jobs_transformed[column].astype(cat_type)
    
    # Convert other columns to categorical type
    else:
        ds_jobs_transformed[column] = ds_jobs_transformed[column].astype('category')

# Filter the DataFrame for records with 10 or more years of experience and company size of at least 1000 employees
ds_jobs_transformed = ds_jobs_transformed[(ds_jobs_transformed['experience'] >= '10') & (ds_jobs_transformed['company_size'] >= '1000-4999')]

brief explanation of what each line of code does:

  1. import pandas as pd: Imports the pandas library for data manipulation.

  2. ds_jobs = pd.read_csv("customer_train.csv"): Loads the dataset from a CSV file into a DataFrame.

  3. ds_jobs_transformed = ds_jobs.copy(): Creates a copy of the original DataFrame for transformations.

  4. for column in ds_jobs.select_dtypes(include='object').columns:: Iterates over columns with object data types.

  5. print(ds_jobs_transformed[column].value_counts(), '\n'): Prints the count of unique values for each object column.

  6. ordered_cats = {...}: Defines ordered categorical mappings for specific columns.

  7. two_factor_cats = {...}: Defines Boolean mappings for two-factor categorical columns.

  8. for column in ds_jobs_transformed:: Iterates over all columns in the DataFrame.

  9. if column in ['relevant_experience', 'job_change']:: Checks if the column is a two-factor category.

  10. ds_jobs_transformed[column] = ds_jobs_transformed[column].map(two_factor_cats[column]): Maps two-factor categories to Boolean values.

  11. elif column in ['student_id', 'training_hours']:: Checks if the column is an integer type.

  12. ds_jobs_transformed[column] = ds_jobs_transformed[column].astype('int32'): Converts integer columns to int32 type.

  13. elif column == 'city_development_index':: Checks if the column is a float type.

  14. ds_jobs_transformed[column] = ds_jobs_transformed[column].astype('float16'): Converts the float column to float16 type.

  15. elif column in ordered_cats:: Checks if the column contains ordered categorical data.

  16. cat_type = pd.CategoricalDtype(categories=ordered_cats[column], ordered=True): Creates an ordered categorical data type.

  17. ds_jobs_transformed[column] = ds_jobs_transformed[column].astype(cat_type): Converts the column to the ordered categorical data type.

  18. else:: For all remaining columns.

  19. ds_jobs_transformed[column] = ds_jobs_transformed[column].astype('category'): Converts the column to a standard categorical data type.

  20. ds_jobs_transformed = ds_jobs_transformed[(ds_jobs_transformed['experience'] >= '10') & (ds_jobs_transformed['company_size'] >= '1000-4999')]: Filters the DataFrame for rows with 10 or more years of experience and company size of at least 1000 employees.