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:
| Column | Description |
|---|---|
student_id | A unique ID for each student. |
city | A code for the city the student lives in. |
city_development_index | A scaled development index for the city. |
gender | The student's gender. |
relevant_experience | An indicator of the student's work relevant experience. |
enrolled_university | The type of university course enrolled in (if any). |
education_level | The student's education level. |
major_discipline | The educational discipline of the student. |
experience | The student's total work experience (in years). |
company_size | The number of employees at the student's current employer. |
company_type | The type of company employing the student. |
last_new_job | The number of years between the student's current and previous jobs. |
training_hours | The number of hours of training completed. |
job_change | An indicator of whether the student is looking for a new job (1) or not (0). |
# Import necessary libraries
import pandas as pd
import numpy as np
from pandas.api.types import CategoricalDtype
# Load the dataset
ds_jobs = pd.read_csv("customer_train.csv")
# View the dataset
ds_jobs.head()To meet these requirements, you can write a function that processes a DataFrame to convert its columns based on their characteristics. Here’s an example implementation in Python:
- Convert columns with two unique categories to booleans.
- Convert integer columns to 32-bit integers.
- Convert float columns to 16-bit floats.
- Convert nominal categorical data to the category data type.
- Convert ordinal categorical data to ordered categories.
1 hidden cell
import pandas as pd
# Assuming ds_jobs is already loaded from 'customer_train.csv'
# ds_jobs = pd.read_csv('customer_train.csv')
# Create a copy of ds_jobs for transforming
ds_jobs_transformed = ds_jobs.copy()
def convert_columns(df, ordinal_columns):
"""
Convert columns of a DataFrame based on their characteristics.
Args:
- df: DataFrame to be converted
- ordinal_columns: Dictionary containing ordinal columns as keys and their ordered categories as values
Returns:
- Converted DataFrame
"""
for column in df.columns:
if column in ordinal_columns:
# Convert ordinal categorical data to ordered categories
categories = ordinal_columns[column]
dtype = pd.CategoricalDtype(categories=categories, ordered=True)
df[column] = df[column].astype(dtype)
elif df[column].dtype == 'object' and df[column].nunique() == 2:
# Convert columns with two unique categories to boolean
df[column] = df[column].astype('bool')
elif pd.api.types.is_integer_dtype(df[column]):
# Convert integer columns to 32-bit integers
df[column] = df[column].astype('int32')
elif pd.api.types.is_float_dtype(df[column]) and df[column].nunique() == 2:
# Convert float columns with two unique values to boolean
df[column] = df[column].astype('bool')
elif pd.api.types.is_float_dtype(df[column]):
# Convert float columns to 16-bit floats
df[column] = df[column].astype('float16')
elif df[column].dtype == 'object':
# Convert nominal categorical data to category data type
df[column] = df[column].astype('category')
return df
# Define the order for the ordinal columns
ordinal_columns = {
"education_level": ['Primary School', 'High School', 'Graduate', 'Masters', 'Phd'],
'experience': ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','>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'],
'enrolled_university': ['no_enrollment', 'Part time course', 'Full time course']
}
ds_jobs_transformed = convert_columns(ds_jobs_transformed, ordinal_columns)
# Adjust the filter conditions to match the specified criteria
# Note: The filtering for 'experience' and 'company_size' needs to be adjusted to work with categorical data
experience_order = ordinal_columns['experience'].index('10')
company_size_order = ordinal_columns['company_size'].index('1000-4999')
filter_condition = (ds_jobs_transformed['experience'].cat.codes >= experience_order) & \
(ds_jobs_transformed['company_size'].cat.codes >= company_size_order)
# Apply the filter condition and retrieve the filtered DataFrame
ds_jobs_transformed = ds_jobs_transformed.loc[filter_condition]