Workspace
Koryo Kakinoki/

Project: Customer Analytics: Preparing Data for Modeling

0
Beta
Spinner

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

The Head Data Scientist at Training Data Ltd. has asked you to create a DataFrame called ds_jobs_clean that stores the data in customer_train.csv much more efficiently. Specifically, they have set the following requirements:

  1. Columns containing integers must be stored as 32-bit integers (int32).
  2. Columns containing floats must be stored as 16-bit floats (float16).
  3. Columns containing nominal categorical data must be stored as the category data type.
  4. Columns containing ordinal categorical data must be stored as ordered categories, and not mapped to numerical values, with an order that reflects the natural order of the column.
  5. The columns of ds_jobs_clean must be in the same order as the original dataset.
  6. The DataFrame should be filtered to only contain students with 10 or more years of experience at companies with at least 1000 employees, as their recruiter base is suited to more experienced professionals at enterprise companies. If you call .info() or .memory_usage() methods on ds_jobs and ds_jobs_clean after you've preprocessed it, you should notice a substantial decrease in memory usage.
import pandas as pd

# Import the CSV
ds_jobs = pd.read_csv('customer_train.csv')

# First look of the data
#display(ds_jobs.head())
display(ds_jobs.info())
#display(ds_jobs.describe())
#display(ds_jobs.memory_usage())
#display(ds_jobs.isna().sum())

# Create a copy of the dataset
ds_jobs_clean = ds_jobs.copy()

# All-in-one code, more efficient way.

# Create a dictionary for ordered categories
ordered_categories = {
    'relevant_experience':['Has relevant experience', 'No relevant experience'],
    'enrolled_university':['no_enrollment', 'Full time course', 'Part 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'],
}

# Change types accordingly by using for loop.
for col in ds_jobs_clean.columns:
    
    # int -> int32
    if ds_jobs_clean[col].dtype == 'int':
        ds_jobs_clean[col] = ds_jobs_clean[col].astype('int32')
    
    # float -> float16
    elif ds_jobs_clean[col].dtype == 'float':
        ds_jobs_clean[col] = ds_jobs_clean[col].astype('float16')
    
    # ordinal categories
    elif col in ordered_categories.keys():
        category = pd.CategoricalDtype(ordered_categories[col], ordered=True)
        ds_jobs_clean[col] = ds_jobs_clean[col].astype(category)
    
    # nominal categories
    else:
        ds_jobs_clean[col] = ds_jobs_clean[col].astype('category')
        
        
display(ds_jobs_clean.info())

# Apply condition: students with >=10 experience & companies with >= 1000 emp
ds_jobs_clean = ds_jobs_clean[(ds_jobs_clean['experience'] >= '10') & (ds_jobs_clean['company_size'] >= '1000-4999')]

ds_jobs_clean.info()
# Model Answer

import pandas as pd

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

# Copy the DataFrame for cleaning
ds_jobs_clean = ds_jobs.copy()

# Create a dictionary of columns containing ordered categorical data
ordered_cats = {
    'relevant_experience': ['No relevant experience', 'Has relevant experience'],
    '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 DataFrame columns to efficiently change data types
for col in ds_jobs_clean:
    
    # Convert integer columns to int32
    if ds_jobs_clean[col].dtype == 'int':
        ds_jobs_clean[col] = ds_jobs_clean[col].astype('int32')
    
    # Convert float columns to float16
    elif ds_jobs_clean[col].dtype == 'float':
        ds_jobs_clean[col] = ds_jobs_clean[col].astype('float16')
    
    # Convert columns containing ordered categorical data to ordered categories using dict
    elif col in ordered_cats.keys():
        category = pd.CategoricalDtype(ordered_cats[col], ordered=True)
        ds_jobs_clean[col] = ds_jobs_clean[col].astype(category)
    
    # Convert remaining columns to standard categories
    else:
        ds_jobs_clean[col] = ds_jobs_clean[col].astype('category')
        
# Filter students with 10 or more years experience at companies with at least 1000 employees
ds_jobs_clean = ds_jobs_clean[(ds_jobs_clean['experience'] >= '10') & (ds_jobs_clean['company_size'] >= '1000-4999')]

display(ds_jobs_clean.info())
Hidden output
  • AI Chat
  • Code