Project: Customer Analytics- Preparing Data for Modeling

Two data scientists working on a dashboard.

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.
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).
# Start your code here!
import pandas as pd
import numpy as np
ds_jobs=pd.read_csv("customer_train.csv")
ds_jobs.shape
(19158, 14)
ds_jobs.head(4)

student_id

city

city_development_index

gender

relevant_experience

enrolled_university

education_level

major_discipline

experience

company_size

company_type

last_new_job

training_hours

job_change

0

8949

city_103

0.920

Male

Has relevant experience

no_enrollment

Graduate

STEM

>20

NaN

NaN

1

36

1

1

29725

city_40

0.776

Male

No relevant experience

no_enrollment

Graduate

STEM

15

50-99

Pvt Ltd

>4

47

0

2

11561

city_21

0.624

NaN

No relevant experience

Full time course

Graduate

STEM

5

NaN

NaN

never

83

0

3

33241

city_115

0.789

NaN

No relevant experience

NaN

Graduate

Business Degree

<1

NaN

Pvt Ltd

never

52

1

ds_jobs.memory_usage().sum()
2145824
ds_jobs.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 19158 entries, 0 to 19157
Data columns (total 14 columns):
 #   Column                  Non-Null Count  Dtype  
---  ------                  --------------  -----  
 0   student_id              19158 non-null  int64  
 1   city                    19158 non-null  object 
 2   city_development_index  19158 non-null  float64
 3   gender                  14650 non-null  object 
 4   relevant_experience     19158 non-null  object 
 5   enrolled_university     18772 non-null  object 
 6   education_level         18698 non-null  object 
 7   major_discipline        16345 non-null  object 
 8   experience              19093 non-null  object 
 9   company_size            13220 non-null  object 
 10  company_type            13018 non-null  object 
 11  last_new_job            18735 non-null  object 
 12  training_hours          19158 non-null  int64  
 13  job_change              19158 non-null  int64  
dtypes: float64(1), int64(3), object(10)
memory usage: 2.0+ MB

Task 1

Columns containing integers must be stored as 32-bit integers (int32).

int_columns = ds_jobs.select_dtypes(include='int64').columns.tolist()
int_columns
['student_id', 'training_hours', 'job_change']
ds_jobs[int_columns]=ds_jobs[int_columns].astype('int32')
ds_jobs.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 19158 entries, 0 to 19157
Data columns (total 14 columns):
 #   Column                  Non-Null Count  Dtype  
---  ------                  --------------  -----  
 0   student_id              19158 non-null  int32  
 1   city                    19158 non-null  object 
 2   city_development_index  19158 non-null  float64
 3   gender                  14650 non-null  object 
 4   relevant_experience     19158 non-null  object 
 5   enrolled_university     18772 non-null  object 
 6   education_level         18698 non-null  object 
 7   major_discipline        16345 non-null  object 
 8   experience              19093 non-null  object 
 9   company_size            13220 non-null  object 
 10  company_type            13018 non-null  object 
 11  last_new_job            18735 non-null  object 
 12  training_hours          19158 non-null  int32  
 13  job_change              19158 non-null  int32  
dtypes: float64(1), int32(3), object(10)
memory usage: 1.8+ MB

Task 2

Columns containing floats must be stored as 16-bit floats (float16).

float_columns = ds_jobs.select_dtypes(include='float64').columns.tolist()
ds_jobs[float_columns]=ds_jobs[float_columns].astype("float16")
ds_jobs.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 19158 entries, 0 to 19157
Data columns (total 14 columns):
 #   Column                  Non-Null Count  Dtype  
---  ------                  --------------  -----  
 0   student_id              19158 non-null  int32  
 1   city                    19158 non-null  object 
 2   city_development_index  19158 non-null  float16
 3   gender                  14650 non-null  object 
 4   relevant_experience     19158 non-null  object 
 5   enrolled_university     18772 non-null  object 
 6   education_level         18698 non-null  object 
 7   major_discipline        16345 non-null  object 
 8   experience              19093 non-null  object 
 9   company_size            13220 non-null  object 
 10  company_type            13018 non-null  object 
 11  last_new_job            18735 non-null  object 
 12  training_hours          19158 non-null  int32  
 13  job_change              19158 non-null  int32  
dtypes: float16(1), int32(3), object(10)
memory usage: 1.7+ MB

Task 3

Columns containing nominal categorical data must be stored as the category data type.

ds_jobs.columns
Index(['student_id', 'city', 'city_development_index', 'gender',
       'relevant_experience', 'enrolled_university', 'education_level',
       'major_discipline', 'experience', 'company_size', 'company_type',
       'last_new_job', 'training_hours', 'job_change'],
      dtype='object')
ds_jobs.head(6)

student_id

city

city_development_index

gender

relevant_experience

enrolled_university

education_level

major_discipline

experience

company_size

company_type

last_new_job

training_hours

job_change

0

8949

city_103

0.919922

Male

Has relevant experience

no_enrollment

Graduate

STEM

>20

NaN

NaN

1

36

1

1

29725

city_40

0.775879

Male

No relevant experience

no_enrollment

Graduate

STEM

15

50-99

Pvt Ltd

>4

47

0

2

11561

city_21

0.624023

NaN

No relevant experience

Full time course

Graduate

STEM

5

NaN

NaN

never

83

0

3

33241

city_115

0.789062

NaN

No relevant experience

NaN

Graduate

Business Degree

<1

NaN

Pvt Ltd

never

52

1

4

666

city_162

0.767090

Male

Has relevant experience

no_enrollment

Masters

STEM

>20

50-99

Funded Startup

4

8

0

5

21651

city_176

0.764160

NaN

Has relevant experience

Part time course

Graduate

STEM

11

NaN

NaN

1

24

1

nominal_cat_columns=['city', 'gender','enrolled_university', 'major_discipline', 'company_type']
ds_jobs[nominal_cat_columns]=ds_jobs[nominal_cat_columns].astype("category")
ds_jobs.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 19158 entries, 0 to 19157
Data columns (total 14 columns):
 #   Column                  Non-Null Count  Dtype   
---  ------                  --------------  -----   
 0   student_id              19158 non-null  int32   
 1   city                    19158 non-null  category
 2   city_development_index  19158 non-null  float16 
 3   gender                  14650 non-null  category
 4   relevant_experience     19158 non-null  object  
 5   enrolled_university     18772 non-null  category
 6   education_level         18698 non-null  object  
 7   major_discipline        16345 non-null  category
 8   experience              19093 non-null  object  
 9   company_size            13220 non-null  object  
 10  company_type            13018 non-null  category
 11  last_new_job            18735 non-null  object  
 12  training_hours          19158 non-null  int32   
 13  job_change              19158 non-null  int32   
dtypes: category(5), float16(1), int32(3), object(5)
memory usage: 1.1+ MB

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

ds_jobs["education_level"].unique()
array(['Graduate', 'Masters', 'High School', nan, 'Phd', 'Primary School'],
      dtype=object)
education_order=['Primary School','High School','Graduate', 'Masters',  'Phd', 'nan' ]
ds_jobs["education_level"]=pd.Categorical(ds_jobs["education_level"],ordered=True,categories=education_order)
ds_jobs.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 19158 entries, 0 to 19157
Data columns (total 14 columns):
 #   Column                  Non-Null Count  Dtype   
---  ------                  --------------  -----   
 0   student_id              19158 non-null  int32   
 1   city                    19158 non-null  category
 2   city_development_index  19158 non-null  float16 
 3   gender                  14650 non-null  category
 4   relevant_experience     19158 non-null  object  
 5   enrolled_university     18772 non-null  category
 6   education_level         18698 non-null  category
 7   major_discipline        16345 non-null  category
 8   experience              19093 non-null  object  
 9   company_size            13220 non-null  object  
 10  company_type            13018 non-null  category
 11  last_new_job            18735 non-null  object  
 12  training_hours          19158 non-null  int32   
 13  job_change              19158 non-null  int32   
dtypes: category(6), float16(1), int32(3), object(4)
memory usage: 978.9+ KB
ds_jobs["relevant_experience"].unique()
order=['No relevant experience','Has relevant experience']
ds_jobs["relevant_experience"]=pd.Categorical(ds_jobs["relevant_experience"],ordered=True,categories=order)
ds_jobs["enrolled_university"].unique()
order=['no_enrollment','Part time course','Full time course','NaN']
ds_jobs["enrolled_university"]=pd.Categorical(ds_jobs["enrolled_university"],ordered=True,categories=order)
order=['<1','1','2', '3',  '4','5','6', '7',  '8','9','10','11','12', '13',  '14','15','16', '17',  '18','19', '20','>20','nan' ]
ds_jobs["experience"].unique()
array(['>20', '15', '5', '<1', '11', '13', '7', '17', '2', '16', '1', '4',
       '10', '14', '18', '19', '12', '3', '6', '9', '8', '20', nan],
      dtype=object)
order=['<1','1','2', '3',  '4','5','6', '7',  '8','9','10','11','12', '13',  '14','15','16', '17',  '18','19', '20','>20','nan' ]
ds_jobs["experience"]=pd.Categorical(ds_jobs["experience"],ordered=True,categories=order)
ds_jobs.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 19158 entries, 0 to 19157
Data columns (total 14 columns):
 #   Column                  Non-Null Count  Dtype   
---  ------                  --------------  -----   
 0   student_id              19158 non-null  int32   
 1   city                    19158 non-null  category
 2   city_development_index  19158 non-null  float16 
 3   gender                  14650 non-null  category
 4   relevant_experience     19158 non-null  category
 5   enrolled_university     18772 non-null  category
 6   education_level         18698 non-null  category
 7   major_discipline        16345 non-null  category
 8   experience              19093 non-null  category
 9   company_size            13220 non-null  object  
 10  company_type            13018 non-null  category
 11  last_new_job            18735 non-null  object  
 12  training_hours          19158 non-null  int32   
 13  job_change              19158 non-null  int32   
dtypes: category(8), float16(1), int32(3), object(2)
memory usage: 717.9+ KB
ds_jobs["company_size"].unique()
array([nan, '50-99', '<10', '10000+', '5000-9999', '1000-4999', '10-49',
       '100-499', '500-999'], dtype=object)
order=['<10','10-49','50-99', '100-499',  '500-999','1000-4999','5000-9999','10000+','nan']
ds_jobs["company_size"]=pd.Categorical(ds_jobs["company_size"],ordered=True,categories=order)
ds_jobs.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 19158 entries, 0 to 19157
Data columns (total 14 columns):
 #   Column                  Non-Null Count  Dtype   
---  ------                  --------------  -----   
 0   student_id              19158 non-null  int32   
 1   city                    19158 non-null  category
 2   city_development_index  19158 non-null  float16 
 3   gender                  14650 non-null  category
 4   relevant_experience     19158 non-null  category
 5   enrolled_university     18772 non-null  category
 6   education_level         18698 non-null  category
 7   major_discipline        16345 non-null  category
 8   experience              19093 non-null  category
 9   company_size            13220 non-null  category
 10  company_type            13018 non-null  category
 11  last_new_job            18735 non-null  object  
 12  training_hours          19158 non-null  int32   
 13  job_change              19158 non-null  int32   
dtypes: category(9), float16(1), int32(3), object(1)
memory usage: 587.3+ KB
ds_jobs["last_new_job"].unique()
array(['1', '>4', 'never', '4', '3', '2', nan], dtype=object)
order=['never','1','2', '3',  '4','>4','nan']
ds_jobs["last_new_job"]=pd.Categorical(ds_jobs["last_new_job"],ordered=True,categories=order)
ds_jobs.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 19158 entries, 0 to 19157
Data columns (total 14 columns):
 #   Column                  Non-Null Count  Dtype   
---  ------                  --------------  -----   
 0   student_id              19158 non-null  int32   
 1   city                    19158 non-null  category
 2   city_development_index  19158 non-null  float16 
 3   gender                  14650 non-null  category
 4   relevant_experience     19158 non-null  category
 5   enrolled_university     18772 non-null  category
 6   education_level         18698 non-null  category
 7   major_discipline        16345 non-null  category
 8   experience              19093 non-null  category
 9   company_size            13220 non-null  category
 10  company_type            13018 non-null  category
 11  last_new_job            18735 non-null  category
 12  training_hours          19158 non-null  int32   
 13  job_change              19158 non-null  int32   
dtypes: category(10), float16(1), int32(3)
memory usage: 456.7 KB
ds_jobs['company_size'].cat.categories[5]
'1000-4999'
x=ds_jobs['experience']>=ds_jobs['experience'].cat.categories[10]
y = ds_jobs['company_size']>=ds_jobs['company_size'].cat.categories[5]
ds_jobs_clean = ds_jobs[x & y]
ds_jobs_clean.head(10)

student_id

city

city_development_index

gender

relevant_experience

enrolled_university

education_level

major_discipline

experience

company_size

company_type

last_new_job

training_hours

job_change

9

699

city_103

0.919922

NaN

Has relevant experience

no_enrollment

Graduate

STEM

17

10000+

Pvt Ltd

>4

123

0

12

25619

city_61

0.913086

Male

Has relevant experience

no_enrollment

Graduate

STEM

>20

1000-4999

Pvt Ltd

3

23

0

31

22293

city_103

0.919922

Male

Has relevant experience

Part time course

Graduate

STEM

19

5000-9999

Pvt Ltd

>4

141

0

34

26494

city_16

0.910156

Male

Has relevant experience

no_enrollment

Graduate

Business Degree

12

5000-9999

Pvt Ltd

3

145

0

40

2547

city_114

0.925781

Female

Has relevant experience

Full time course

Masters

STEM

16

1000-4999

Public Sector

2

14

0

47

25987

city_103

0.919922

Other

Has relevant experience

no_enrollment

Graduate

STEM

19

10000+

Public Sector

4

52

1

104

1180

city_16

0.910156

Male

Has relevant experience

no_enrollment

Graduate

STEM

12

5000-9999

Pvt Ltd

1

52

0

108

25349

city_16

0.910156

Male

Has relevant experience

no_enrollment

Graduate

STEM

>20

1000-4999

Pvt Ltd

>4

28

0

115

20576

city_97

0.924805

Male

Has relevant experience

no_enrollment

Graduate

STEM

>20

1000-4999

Pvt Ltd

>4

19

0

130

3921

city_36

0.893066

NaN

No relevant experience

no_enrollment

Phd

STEM

>20

1000-4999

Public Sector

>4

4

0

ds_jobs_clean.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2201 entries, 9 to 19143
Data columns (total 14 columns):
 #   Column                  Non-Null Count  Dtype   
---  ------                  --------------  -----   
 0   student_id              2201 non-null   int32   
 1   city                    2201 non-null   category
 2   city_development_index  2201 non-null   float16 
 3   gender                  1821 non-null   category
 4   relevant_experience     2201 non-null   category
 5   enrolled_university     2185 non-null   category
 6   education_level         2184 non-null   category
 7   major_discipline        2097 non-null   category
 8   experience              2201 non-null   category
 9   company_size            2201 non-null   category
 10  company_type            2144 non-null   category
 11  last_new_job            2184 non-null   category
 12  training_hours          2201 non-null   int32   
 13  job_change              2201 non-null   int32   
dtypes: category(10), float16(1), int32(3)
memory usage: 76.3 KB

DataCamp Codes

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')]