Staff feedback provides the companies with valuable information on the reasons why employees resign or retire. This information is used to inform attraction and retention initiatives and to improve work practices across to any company to ensure the company is considered an employer of choice.
Source: flexjobs
In this project, we'll work with exit surveys from employees of the Department of Education, Training and Employment) (DETE) and the Technical and Further Education (TAFE) institude in Queensland, Australia.
The DETE Exit Survey was developed to effectively canvas the opinions and attitudes of departing employees to identify a wide range of operational, organizational and personal variables affecting the decision to leave.
We can find the DETE exit survey data here. However, the orignial TAFE exit survey data is no longer available.
Therefore, we'll be using the modified versions of the original datasets to make them easier to work with, which includes changing the encoding to UTF-8
(the original ones are encoded using cp1252
).
The data dictionary wasn't provided with the datasets. Therefore, we'll use our general knowledge to define the columns used in them.
Below is a preview of a couple columns we'll work with from the dete_survey.csv
:
ID
: An id used to identify the participant of the surveySeparationType
: The reason why the person's employment endedCease Date
: The year or month the person's employment endedDETE Start Date
: The year the person began employment with the DETEBelow is a preview of a couple columns we'll work with from the tafe_survey.csv
:
Record ID
: An id used to identify the participant of the surveyReason for ceasing employment
: The reason why the person's employment endedLengthofServiceOverall. Overall Length of Service at Institute (in years)
: The length of the person's employment (in years)In this project, we'll analyze these datasets (DETE & TAFE) to find out the answers of the following questions:
We'll combine the resluts for both surveys to answer these questions. However, although both used the same survey template, one of them customized some of the answers.
We'll start by importing some useful libraries we need in the project.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.style as style
# Display all columns in the dataframe
pd.set_option('display.max_columns', None)
# Enable the inline plotting
%matplotlib inline
Next, we'll read in the dete_survey.csv
and tafe_survey.csv
datasets into pandas and explore them.
# Read datasets
dete_survey = pd.read_csv('dete_survey.csv')
tafe_survey = pd.read_csv('tafe_survey.csv')
Now that our datasets are loaded, we'll gather some basic information about both dataframes using DataFrame.info()
and take a took at first few rows using DataFrame.head()
.
# Preview DETE dataset
dete_survey.info()
dete_survey.head()
Interestingly, there are some important key points in the dataset that we need to consider:
ID
is stored as int, and rest of the columns have object dtypes.Classification
has arount 44%, whereas, Business Unit
, Aboriginal
, Torres Strait
, South Sea
, Disability
, and NESB
have more than 50% missing values.Cease Date
, DETE Start Date
, and Role Start Date
are stored as string dtypes instead of datetime.Let's look at descriptive statistics using describe(include='all')
. The parameter all with describe()
method allows all columns to include in the output.
dete_survey.describe(include='all')
Here decribe(include='all)
method helps us further to get clarity and better understanding about our data:
SeparationType
column.Age
column which further solidify the reason why employees exit from DETE.DETE Start Date
and Role Start Date
columns have Not Stated as most frequent value and it should be referred as NaN.Aboriginal
, Torres Strait
, South Sea
, Disability
, and NESB
have one unique value which is Yes and all other values are stored as NaN, rather they should be stored as No. This is the reason why these columns have such a high percentage of missing values.Professional Development
to Health & Safety
have A as most common values. This seems quite unusual as 'A' doesn't seem to represent anything. We'll explore these columns further.To investigate the unusual entries like 'A' in the columns from Professional Development
to Health & Safety
, we'll have to find all the unique values and count them. For this purpose, first we'll use pandas DataFrame.apply()
on our target columns and then we'll count unique values using lambda
function.
dete_survey.loc[:, 'Professional Development':'Health & Safety'].apply(lambda x: x.value_counts())
Observation
SA
, M
, A
, N
, D
, SD
.M
means in these columns. Since the data source has not provided the description, we'll assume that it is likely to be abbreviated as Missing (i.e. the individual did not select an option). A
in every column.# Preview TAFE dataset
tafe_survey.info()
tafe_survey.head()
We notice that the presentation of the tafe_survey
dataset is a lot more messier than the dete_survey
dataset in contrast, we makes it harder to analyze the data. We need to pay careful attention to extract the key points from this dataset:
Record ID
and CESSATION YEAR
) are stored as float.Main Factor. Which of these was the main factor for leaving?
has the highest about 84% of missing values in the whole dataset.CESSATION YEAR
, Reason for ceasing employment
, Gender
, CurrentAge
, and EmploymentType
.Let's dig deeper and gather some more insights with the help of describe(include='all')
.
tafe_survey.describe(include='all')
There are various issues in the data that are important to highligth:
Contributing Factors
columns have -
. This could be indicating that no answer was provided at the time the survey was administered.Main Factor. Which of these was the main factor for leaving?
column is Dissatisfaction with Institute which appears 23 times only. We have to consider that this column has over 83% of missing values as well.Reason for ceasing employment
shows the reason why most employees leave the work and that is Resignation.InstituteViews
and WorkUnitViews
have recorded Agree most of the time. Similiar to DETE data.CurrentAge. Current Age
column has several age bins. Most of them are 56 years or older.Brief Description of the Oberservations
From our initial work, we can first make the following observations:
dete_survey
dataframe contains Not Stated
values that indicate values are missing, but they aren't represented as NaN
.dete_survey
and tafe_survey
dataframes contain many columns that we don't need to complete our analysis.Let's take care of these issues next.
To start, we'll handle the first two issues. We can use the pd.read_csv()
function to specify values that should be represented as NaN
. We'll use this function to fix the missing values first. Then, we'll drop columns we know we don't need for our analysis.
We read the dete_survey.csv
file into pandas again, but this time read the Not Stated
values in as NaN
:
Not Stated
in as NaN
, we'll set the na_values
parameter to Not Stated
in the pd.read_csv()
funtion.dete_survey = pd.read_csv('dete_survey.csv', na_values='Not Stated')
dete_survey.head()
Next, let's drop some columns from each dataframe that we won't use in our analysis to make the dataframes easier to work with:
DataFrame.drop()
method to drop the columns from Professional Development
(column 28) to Health & Safety
(column 48) in dete_survey
. dete_survey_updated
.dete_unwanted_cols = dete_survey.columns[28:49]
dete_survey_updated = dete_survey.drop(dete_unwanted_cols, axis=1)
dete_survey_updated.head()
Now, we'll repeat the same steps for tafe_survey
:
Main Factor. Which of these was the main factor for leaving?
(column 17) to Workplace. Topic:Would you recommend the Institute as an employer to others?
(column 65).tafe_survey_updated
.tafe_unwanted_cols = tafe_survey.columns[17:66]
tafe_survey_updated = tafe_survey.drop(tafe_unwanted_cols, axis=1)
tafe_survey_updated.head()
Let's varify the changes we have made after dropping the columns in both datasets.
print(f'Number of columns in DETE dataset\nbefore cleaning: {dete_survey.shape[1]}\tafter cleaning: {dete_survey_updated.shape[1]}')
print('-'*40)
print(f'Number of columns TAFE dataset\nbefore cleaning: {tafe_survey.shape[1]}\tafter cleaning: {tafe_survey_updated.shape[1]}')
We have made the changes now let's turn our focus to the column names.
Each dataframe contains many of the same columns, but the columns are different. Below are some of the columns we'd like to use for our final analysis:
dete_survey | tafe_survey | Definition |
---|---|---|
ID | Record ID | An id used to identify the participant of the survey |
SeparationType | Reason for ceasing employment | The reason why the participant's employment ended |
Cease Date | CESSATION YEAR | The year or month the participant's employment ended |
DETE Start Date | The year the participant began employment with the DETE | |
LengthofServiceOverall. Overall Length of Service at Institute (in years) | The length of the person's employment (in years) | |
Age | CurrentAge. Current Age | The age of the participant |
Gender | Gender. What is your Gender? | The gender of the participant |
Because we eventually want to combine them, we'll have to standardize the column names. Let's begin with dete_survey_updated
dataframe using the following criteria to update the column names:
DataFrame.columns
attribute along with vectorized string methods to update all of the columns at once._
).dete_survey_updated.columns = dete_survey_updated.columns.str.lower().str.strip().str.replace('\s+', '_', regex=True)
dete_survey_updated.columns
Next, we'll update the columns in the tafe_survey_updated
using DataFrame.rename()
method. For this purpose, we'll take the following steps:
dete_survey_updated
dataframe.cols_to_rename = {
'Record ID': 'id',
'CESSATION YEAR': 'cease_date',
'Reason for ceasing employment': 'separationtype',
'Gender. What is your Gender?': 'gender',
'CurrentAge. Current Age': 'age',
'Employment Type. Employment Type': 'employment_status',
'Classification. Classification': 'position',
'LengthofServiceOverall. Overall Length of Service at Institute (in years)': 'institute_service',
'LengthofServiceCurrent. Length of Service at current workplace (in years)': 'role_service'
}
tafe_survey_updated.rename(columns=cols_to_rename, inplace=True)
Let's use the DataFrame.head()
method to look at the current state of the dete_survey_updated
and tafe_survey_updated
dataframes and make sure the changes have taken place.
# View 'dete_survey_updated' dataframe
dete_survey_updated.head(2)
# View 'tafe_survey_updated' dataframe
tafe_survey_updated.head(2)
We have renamed the columns that we'll use in our analysis. Next, let's remove more of the data we don't need.
Recall that one of our end goals is to answer the following question:
If we look at the unique values in the separationtype
columns in each dataframe, we'll see that each contains a couple of different separation types.
dfs = [dete_survey_updated, tafe_survey_updated]
df_names = ['DETE Survey Data', 'Tafe Survey Data']
for df, df_name in zip(dfs, df_names):
print('\033[1m' + df_name + '\033[0;0m')
print(df['separationtype'].value_counts(dropna=False), '\n')
We'll only analyze survey respondents who resigned, so their separation type contains the string Resignation
. Note above that we can see multiple separation types with the string Resignation
, such as:
We'll have to account for each of these variations so we don't unintentionally drop data.
Also, we'll use the DataFrame.copy()
method on the result to avoid the SettingWithCopy Warning.
# Select only those entries that have a 'Resignation' separation type
dete_resignations = dete_survey_updated[dete_survey_updated['separationtype'].str.contains('Resignation')].copy()
# str.contains method can not mask non-boolean values
# therefore, specifying 'na' to 'False' in the parameter
tafe_resignations = tafe_survey_updated[tafe_survey_updated['separationtype'].str.contains('Resignation', na=False)].copy()
# Display unique values in 'dete_resignations' and 'tafe_resignations'
for df, df_name in zip([dete_resignations, tafe_resignations], df_names):
print('\033[1m' + df_name + '\033[0;0m')
print(df['separationtype'].value_counts(), '\n')
Now, before we start cleaning and manipulating the rest of our data, let's verify that the data doesn't contain any major inconsistencies.
In this step, we'll focus on verifying that the years in the cease_date
and dete_start_date
columns make sense. We'll check the date for the following issues:
cease_date
is the last year of the person's employment and the dete_start_date
is the person's first year of employment, it wouldn't make sense to have years after the current date.dete_start_date
was before the year 1940.Let's view the unique values in the cease_date
column first.
dete_resignations['cease_date'].value_counts()
The values in the cease_date
column are inconsistent. Some dates are stored as just years in YYYY format, whereas, others are in MM/YYYY format.
We'll deal with this issue by extracting only year values from the column and convert the data type to float (the year values stored in other columns are float as well).
# Create regex to match 4 digits of year
pattern = r'(\d{4})'
# Extract and assign only year from 'cease_date' and convert the type to float
dete_resignations['cease_date'] = dete_resignations['cease_date'].str.extract(pattern).astype('float')
Let's count the unique values again in the cease_date
column.
# View unique values in 'cease_date' with index in ascending order
dete_resignations['cease_date'].value_counts().sort_index()
We can see the result of these unique values is uniform. Now we'll explore the dete_start_date
column in dete_resignations
.
# View unique values in 'dete_start_date'
dete_resignations['dete_start_date'].value_counts().sort_index()
There is no inconsistent pattern in the column and the values are correctly formated.
Lastly, find the unique values in cease_date
column of tafe_resignations
dataframe.
# View unique values with index in ascending order
tafe_resignations['cease_date'].value_counts().sort_index()
The values in this column look uniform as well. Now, we'll move on to visualize the values of dete_start_date
and cease_date
columns with a boxplot
to identify any values that look wrong.
dete_resignations.boxplot(column=['dete_start_date', 'cease_date'], color='darkred')
plt.title('DETE Employees Data Who Resigned', fontsize=15, fontweight='bold')
plt.ylabel('Year', fontsize=15)
plt.ylim(1960, 2020)
plt.show()
We gain the following insights from the figure above:
cease_date
(i.e. 2013).1990's
to 2010
.2010 - 2013
year bracket.Since we do not have the information about job starting year in the tafe_resignations
, it won't really be helpful to make visualization on this dataframe.
Now that we've verified that there aren't any major issues with years in the dete_resignations
dataframe, we'll use them to create a new column. Recall that our end goal is to answer the following question:
We have noticed that the tafe_resignations
dateframe already contains a column institute_service
which refers to years of service of an employee. In order to analyze both surveys together, we'll have to create a corresponding institute_service
column in dete_resignations
. We can create the institute_service
column by subtracting the dete_start_date
from the cease_date
.
dete_resignations['institute_service'] = dete_resignations['cease_date'] - dete_resignations['dete_start_date']
dete_resignations['institute_service']
Let's group the years from institute_service
column into different bins. To create binning we'll have to make a custom function year_group()
because for most of the groups we want to include both left and right edges, therefore, pd.cut won't be useful.
We'll group the years in a same way as they are in the institute_service
column of tafe_resignations
dataframe:
def year_group(n):
"""
Perform operation on each element of a column to group them.
Param:
n (float/int): A value in the column.
Returns:
A category representing the respective bin for a given value n.
"""
if n < 1:
return 'Less than 1 year'
elif 1 <= n <= 2:
return '1-2'
elif 3 <= n <= 4:
return '3-4'
elif 5 <= n <= 6:
return '5-6'
elif 7 <= n <= 10:
return '7-10'
elif 11 <= n <= 20:
return '11-20'
else:
return 'More than 20 years'
Next, we'll call our customize function on the institute_service
column using Series method apply()
and assign the result to a new column institute_service_year_group
. Note: we'll have to make sure the our function doesn't not compute NaN
values and that's what the lambda
function is doing in the code cell below.
dete_resignations['institute_service_year_group'] = dete_resignations['institute_service'].apply(lambda x: year_group(x) if pd.notnull(x) else x)
Let's calculate the frequency of institute_service_year_group
column in dete_resignations
dateframe.
dete_resignations['institute_service_year_group'].value_counts(dropna=False).sort_index(ascending=False)
We have 38 missing entries and the rest of the result shows that 173 employees (about 56%) resigned from the work at DETE in their first 10 years. Whereas 57 employees (18%) made it up to 20 years before leaving their job, 13% of employees resigned after 20 years of service.
Now we'll move on to TAFE and explore the frequency of institute_service
column.
tafe_resignations['institute_service'].value_counts(dropna=False)
Despite having 50 missing entries, the numbers are staggering in the TAFE data. There are 74% of employees (254 out of 340) resigned within 10 years. Only 10% of employees resigned after 10 years of their service.
Next, we'll identify employees who resigned due to dissatisfaction. Below are the columns we'll use to categorize employees as dissatisfied from each dataframe.
Contributing Factors. Dissatisfaction
Contributing Factors. Job Dissatisfaction
job_dissatisfaction
dissatisfaction_with_the_department
physical_work_environment
lack_of_recognition
lack_of_job_security
work_location
employment_conditions
work_life_balance
workload
If the employee indicated any of the factors above caused them to resign, we'll make them as dissatisfied
in a new column. After our changes, the new dissatisfied
column will contain just the following values:
True
: indicates a person resigned because they were dissatisfied with the jobFalse
: indicates a person resigned because of a reason other than dissatisfaction with the jobNaN
: indicates the value is missingBefore that let's view the unique values in the 'Contributing Factors. Dissatisfaction'
and 'Contributing Factors. Job Dissatisfaction'
columns in the tafe_resignations
dataframe.
# View the values in the 'dissatisfied columns' of tafe_resignations
tafe_dissatisfied_cols = ['Contributing Factors. Dissatisfaction', 'Contributing Factors. Job Dissatisfaction']
for col in tafe_dissatisfied_cols:
print('-'*60)
print(tafe_resignations[col].value_counts(dropna=False))
print('-'*60)
We'll now create a function update_vals
to update the values as we have discussed above.
def update_vals(val):
"""
Take the value of a Series and update it to bool or np.nan
Params:
val (str, NaN, or -): The value to be updated
Returns:
bool or NaN
"""
if pd.isnull(val):
return np.nan
elif val == '-':
return False
else:
return True
Next, we'll use the DataFrame.applymap()
method to apply the update_vals
function to update the values of our columns of interest in the tafe_resignations
dataframe.
tafe_resignations[tafe_dissatisfied_cols] = tafe_resignations[tafe_dissatisfied_cols].applymap(update_vals)
# View the changes in 'tafe_dissatisfied_cols'
for col in tafe_dissatisfied_cols:
print('-'*60)
print(tafe_resignations[col].value_counts(dropna=False))
print('-'*60)
The changes have been made successfully. Now, we'll use the df.any()
method as described above to create a dissatisfied
column in the tafe_resignations
dataframe. Note skipna=False
parameter will treat any missing value in the column as True
.
tafe_resignations['dissatisfied'] = tafe_resignations[tafe_dissatisfied_cols].any(axis=1, skipna=False)
# View the values in the 'dissatisfied' column
tafe_resignations['dissatisfied'].value_counts(dropna=False)
To avoid SettingWithCopy Warning let's make a copy of the tafe_resignations
using df.copy()
and then view the results. We'll assign the new results to tafe_resignations_up
.
tafe_resignations_up = tafe_resignations.copy()
tafe_resignations_up.head()
Now that we have made the changes in the tafe_resignations
dataframe, we'll follow the same steps for dete_resignations
as well:
df.any()
method to create new column dissatisfied
.df.copy()
method to create a copy and assign results to dete_resignations_up
.# View value in values in our targeted columns of `dete_resignations`
dete_dissatisfied_cols = ['job_dissatisfaction', 'dissatisfaction_with_the_department',
'physical_work_environment', 'lack_of_recognition',
'lack_of_job_security', 'work_location',
'employment_conditions', 'work_life_balance',
'workload']
for col in dete_dissatisfied_cols:
print('-'*60)
print(dete_resignations[col].value_counts(dropna=False))
print('-'*60)
We notice that there is no missing values in any of these columns. We'll continue to completed rest of the steps.
# Create new `dissatisfied` column in the `dete_resignations`
dete_resignations['dissatisfied'] = dete_resignations[dete_dissatisfied_cols].any(axis=1, skipna=False)
# Create a copy of `dete_resignations` and assign it to `dete_resignations_up`
dete_resignations_up = dete_resignations.copy()
# View the result
dete_resignations_up.head()
To recap, we've accomplished the following:
institute_service
columnContributing Factors
columnsdissatisfied
indicating if an employee resigned because they were dissatisfied in some wayNow, we're finally ready to combine our datasets! Our end goal is to aggregate the data according to the institute_service
column, so for this purpose we'll take the following steps:
institute
to each dataframe that will allow us to easily distinguish between the two.combined
variable.DataFrame.dropna()
and assign the result to combined_updated
variable.Let's do this next to get the data into a form that's easy to aggregate.
# Add column 'institute' to 'dete_resignations_up'
# that contains the value 'DETE'
dete_resignations_up['institute'] = 'DETE'
# View result
dete_resignations_up.head()
# Add column 'institute' to 'tafe_resignations_up'
# that contains the value 'TAFE'
tafe_resignations_up['institute'] = 'TAFE'
# View result
tafe_resignations_up.head()
# Combine both dataframes
combined = pd.concat([dete_resignations_up, tafe_resignations_up], ignore_index=True)
# View result
combined.head()
# View columns to check the number of non null values
combined.info()
# Drop columns with less than 500 non null values
combined_updated = combined.dropna(axis='columns', thresh=500)
# Check the updated dataframe for confirmation
combined_updated.info()
# View the dataframe
combined_updated.head()
We have combined our dataframes and drop columns with less than 500 non null values.
We're almost at a place where we can perform some kind of analysis but first we'll have to clean up the institute_service
column. The column is a bit tricky to clean because it currently contains values in a couple different forms:
combined_updated['institute_service'].value_counts(dropna=False)
To analyze the data, we'll convert these numbers into categories. We'll base our analysis on this article, which makes the argument that understanding employee's needs according to career stage instead of age is more effective.
To continue, we'll have to apply vectorized string methods on the institute_service
and modify the values to a required format. We'll take the following steps to achieve the desire results:
institute_service
from object to float# Make copy of the 'combined_updated' dataframe to avoid SettingWithCopyWarning
combined_updated2 = combined_updated.copy()
# Replace the values into the required format
combined_updated2['institute_service'] = (combined_updated2['institute_service'].astype('str').str.replace('Less than 1 year', '1', regex=True)
.str.replace('More than 20 years', '21', regex=True)
.str.replace('.', '-', regex=True))
# Split the values to get the 0th element
# and convert data-type to float
combined_updated2['institute_service'] = combined_updated2['institute_service'].str.split('-').str.get(0).astype('float')
# View the values after performing vectorized methods
combined_updated2['institute_service'].value_counts(dropna=False).sort_index()
We have made the changes, now we'll create a years_cat
function to convert the values in institute_service
into categories:
Let's categorize the values in the institute_service
column using the definitions above.
def years_cat(val):
"""
Covert years of service into categories.
Params:
val (float or NaN): The value to be converted
Returns:
NaN or category of the value
"""
if pd.isnull(val):
return np.nan
elif val < 3:
return 'New (0-3)'
elif 3 <= val <= 6:
return 'Experienced (3-6)'
elif 7 <= val <= 10:
return 'Established (7-10)'
else:
return 'Veteran (11+)'
combined_updated2['service_cat'] = combined_updated2['institute_service'].apply(years_cat)
# Check the unique values
combined_updated2['service_cat'].value_counts(dropna=False)
We have successfully cleaned and categorized the institute_service
column. We have stored the categorized data in the new column service_cat
. Now we'll move on the our next column of interest (age
).
Now we'll deal with the next column of interest age
that is required for our analysis. Let's check the values of this column.
combined_updated2['age'].value_counts(dropna=False)
As we can see the values represented in the age
column are irregular. To clean the data we'll use string vectorized method str.extract()
to retrieve first value from each entry. For instance, extract 26 from 26-30 or 20 from 20 or younger and so on. Then we'll convert the data-type into float.
# Extract only first digits from each entry
combined_updated2['age'] = combined_updated2['age'].astype('str').str.extract(r'(\d+)').astype('float')
# View the values
combined_updated2['age'].value_counts()
We have the data in the desired format. We can now convert the age of the employees into categories. Below is a list of different categories we'll use to represent the age:
In order to perform this task we'll create a age_categories()
function which takes the value from age
column and categorize accordingly. We'll store the age-categories in the new column age_cat
.
def age_categories(val):
if pd.isnull(val):
return np.nan
elif val <= 20:
return 'Teen (20 or less)'
elif 21 <= val <= 40:
return 'Young (21-40)'
elif 41 <= val <= 60:
return 'Adults (41-60)'
else:
return 'Senior (61 or more)'
combined_updated2['age_cat'] = combined_updated2['age'].apply(age_categories)
combined_updated2['age_cat'].value_counts(dropna=False)
We have done all the data cleaning for our analysis. Next, we'll deal with the missing values.
Our next step is to check the missing values in the data and how we can handle them. First, let's find the number of missing values in each column of combined_updated2
dataframe.
# Find the number of missing values in each column
combined_updated2.isnull().sum()
We have missing values in almost every column but for now our focus will only be on the service_cat
and age_cat
columns.
Around 15% of the data in the service_cat
column is missing. Therefore, we can't simply replace the missing values with the most frequent values. Instead, we'll have to find a better way. One of the things we can do is use the values in the age_cat
column and fill the missing values in service_cat
accordingly.
Before tackling this challenge, let's see the rows with missing data in service_cat
and visualize their representation.
# Find rows with missing values in 'service_cat'
combined_updated2[combined_updated2['service_cat'].isnull()]
We can notice that more rows have NaN in both service_cat
and age_cat
; we can count these columns having the exact missing values together.
# Find rows of missing values in both 'service_cat' and 'age_cat' columns
missing_serv_age_cat = combined_updated2[(combined_updated2['service_cat'].isnull()) & (combined_updated2['age_cat'].isnull())]
# Total number of rows with missing values
missing_serv_age_cat.shape[0]
There are 53 rows out of 88 that have missing data in both the service_cat
and age_cat
columns. These rows won't be helpful for our analysis. It is safe to drop them.
# Drop the rows that have missing values in both 'service_cat' and 'age_cat' columns
combined_updated2.drop(labels=missing_serv_age_cat.index, inplace=True)
# Reset the index of 'combined_updated2' dataframe
combined_updated2.reset_index(drop=True, inplace=True)
Moving on we'll now count the of missing data in service_cat
based on each institue (DETE or TAFE).
# Count the values of 'service_cat' in the DETE institute
combined_updated2[combined_updated2['institute']=='DETE']['service_cat'].value_counts(dropna=False)
# Count the values of 'service_cat' in the TAFE institute
combined_updated2[combined_updated2['institute']=='TAFE']['service_cat'].value_counts(dropna=False)
We only have missing service categories in the DETE institute. So we'll take the following steps to solve this issue:
combined_updated2
dataframe based on DETE institute according to each age category (e.g. DETE & Teen, DETE & Young, and so on).service_cat
with the most frequent values respectively.Let's begin with the step one which is to make subsets of combined_updated2
dataframes separately.
# Select data that has 'DETE' institute and 'Teen' as age category
dete_teen = combined_updated2[(combined_updated2['institute']=='DETE') & (combined_updated2['age_cat']=='Teen (20 or less)')]
# Select data that has 'DETE' institute and 'Young' as age category
dete_young = combined_updated2[(combined_updated2['institute']=='DETE') & (combined_updated2['age_cat']=='Young (21-40)')]
# Select data that has 'DETE' institute and 'Adults' as age category
dete_adults = combined_updated2[(combined_updated2['institute']=='DETE') & (combined_updated2['age_cat']=='Adults (41-60)')]
# Select data that has 'DETE' institute and 'Senior' as age category
dete_senior = combined_updated2[(combined_updated2['institute']=='DETE') & (combined_updated2['age_cat']=='Senior (61 or more)')]
We have extracted the required data. In the step two we'll count the distribution across each age category.
# View the results of frequent values accordingly to age-categories
print(f"\033[1mDETE Age Category: Teen\033[0;0m\n{dete_teen['service_cat'].value_counts(dropna=False)}\n")
print(f"\033[1mDETE Age Category: Young\033[0;0m\n{dete_young['service_cat'].value_counts(dropna=False)}\n")
print(f"\033[1mDETE Age Category: Adults\033[0;0m\n{dete_adults['service_cat'].value_counts(dropna=False)}\n")
print(f"\033[1mDETE Age Category: Senior\033[0;0m\n{dete_senior['service_cat'].value_counts(dropna=False)}")
Apart from DETE Teen
, all other subsets have missing values which we'll replace with the frequent values. Specially, in DETE Young
we have 12 missing values which we'll fill with Experienced (3-6) because it is the most frequent one. Similarly, in the DETE Adults
and DETE Senior
we'll replace their missing values with Veteran (11+).
# Fill missing values with 'Experienced (3-6)'
combined_updated2.loc[dete_young.index, 'service_cat'] = combined_updated2.loc[dete_young.index, 'service_cat'].fillna('Experienced (3-6)')
# Fill missing values with 'Veteran (11+)'
combined_updated2.loc[dete_adults.index, 'service_cat'] = combined_updated2.loc[dete_adults.index, 'service_cat'].fillna('Veteran (11+)')
# Fill missing values with 'Veteran (11+)'
combined_updated2.loc[dete_senior.index, 'service_cat'] = combined_updated2.loc[dete_senior.index, 'service_cat'].fillna('Veteran (11+)')
We have performed all the step, now the service_cat
column in the combined_updated2
dataframe should not have any missing values. Let's confirm that:
# Find the number of missing values in 'service_cat'
combined_updated2['service_cat'].isnull().sum()
Everything is sorted in the service_cat
, let's move on and deal the age_cat
column.
We'll perform similar tasks like we've done above to handle missing values in the age_cat
but this time will use the values in service_cat
to fill missing data in the age_cat
column. Following are the step that we'll take:
age_cat
combined_updated2
dataframe based on the institute and service categories# Count the values in 'age_cat' column
combined_updated2['age_cat'].value_counts(dropna=False)
# Find the rows with missing values
combined_updated2[combined_updated2['age_cat'].isnull()]
# Select subset data that has 'DETE' institute and 'Veteran' as service category
dete_veteran = combined_updated2[(combined_updated2['institute']=='DETE') & (combined_updated2['service_cat']=='Veteran (11+)')]
# Select subset data that has 'DETE' institute and 'New' as service category
dete_new = combined_updated2[(combined_updated2['institute']=='DETE') & (combined_updated2['service_cat']=='New (0-3)')]
# View the results of frequent values accordingly to service-categories
print(f"\033[1mDETE Service Category: Veteran\033[0;0m\n{dete_veteran['age_cat'].value_counts(dropna=False)}\n")
print(f"\033[1mDETE Service Category: New\033[0;0m\n{dete_new['age_cat'].value_counts(dropna=False)}")
# Fill missing values with 'Adults (41-60)'
combined_updated2.loc[dete_veteran.index, 'age_cat'] = combined_updated2.loc[dete_veteran.index, 'age_cat'].fillna('Adults (41-60)')
# Fill missing values with 'Young (21-40)'
combined_updated2.loc[dete_new.index, 'age_cat'] = combined_updated2.loc[dete_new.index, 'age_cat'].fillna('Young (21-40)')
# Check the value distribution again in 'age_cat' column
combined_updated2['age_cat'].value_counts(dropna=False)
We have filled the missing values with relevant data in both columns (service_cat
and age_cat
). Let's take a final look at combined_updated2
dataframe to see how much of the missing values have left behind.
combined_updated2.isnull().sum()
As we've expected the missing data is reduced drastically, more importantly our columns of interest service_cat
and age_cat
have no missing data and set for data analysis.
After data cleaning, we're now ready to do our first piece of analysis.
We can calculate the percentage of dissatisfied people who left at different career stage. If we recall, our goal is:
We'll find the percentage of dissatisfaction with each category in the service_cat
column, and sort the values in ascending order. Then, we'll visualize the results to better understand the difference.
# Calculate the percentage of people who resigned
# due to dissatisfaction in each service category
dis_serv_pv = combined_updated2.pivot_table(values='dissatisfied', index='service_cat')
# Sort the categories index
dis_serv_pv.sort_values(by='dissatisfied', inplace=True)
dis_serv_pv['dissatisfied'] = dis_serv_pv['dissatisfied'] * 100
# Plot the results
dis_serv_pv.plot(kind='bar',
title='Category of Dissatisfied Employees Who Resigned')
# Align the x-axis labels
plt.xticks(rotation=45, ha='right')
plt.show()
Observations
We'll perform the same analysis as above. To remind ourselves, our next goal is:
We'll compare dissatisfaction with age
column.
# Calculate the percentage of dissatisfied employees who resigned in each age group
dis_age_pv = combined_updated2.pivot_table(values='dissatisfied', index='age_cat')
dis_age_pv.sort_values(by='dissatisfied', inplace=True)
dis_age_pv['dissatisfied'] = dis_age_pv['dissatisfied'] * 100
# Plot the results
dis_age_pv.plot(kind='bar',
rot=45,
title='Age of Dissatisfied Employees Who Resigned')
plt.show()
Observations
Before we move on to visualize our analysis, we still have to deal with one more scenario.
In addition to our analysis we'll also try to figure out the following question:
We'll calculate each of the institutes (DETE and TAFE) to find out which has the most resignation from dissatisfied people. It can give us a general idea about the distribution.
First thing we need is to extract DETE
and TAFE
separately from institute
column then we'll count the number of dissatisfied employees in each of the institute respectively.
# Create subset of 'combined_updated2' dataframe based on DETE and TAFE
dete_institute = combined_updated2[combined_updated2['institute']=='DETE']
tafe_institute = combined_updated2[combined_updated2['institute']=='TAFE']
# Count the values of dissatisfied employees in DETE and TAFE
dist_dete_count = dete_institute['dissatisfied'].value_counts(dropna=False)
dist_tafe_count = tafe_institute['dissatisfied'].value_counts(dropna=False)
# View results
print(f'\033[1mDissatisfied count in DETE:\033[0;0m\n{dist_dete_count}\n')
print(f'\033[1mDissatisfied count in TAFE:\033[0;0m\n{dist_tafe_count}')
In general, 48% of the employees who left the DETE institue did so because of some dissatisfaction issues which is almost twice higher in percentage than for the TAFE institute which is 26%.
It would be interesting to look into each of the service categories of DETE and TAFE institutes to figure out how they are impacting individually.
# Create subset of 'combined_updated2' dataframe
# based on dete institute
dete_institute = combined_updated2[combined_updated2['institute']=='DETE']
# Find percentage of the dissatisfied employees based on the service categories
pv_dete_institute_serv = dete_institute.pivot_table(index='service_cat', values='dissatisfied')
# Sort the values of 'dissatisfied' column in descending order
pv_dete_institute_serv = pv_dete_institute_serv.sort_values(by='dissatisfied', ascending=False)*100
# Create subset of 'combined_updated2' dataframe
# based on tafe institute
tafe_institute = combined_updated2[combined_updated2['institute']=='TAFE']
# Find percentage of the dissatisfied employees based on the service categories
pv_tafe_institute_serv = tafe_institute.pivot_table(index='service_cat', values='dissatisfied')
# Sort the values of 'dissatisfied' column in descending order
pv_tafe_institute_serv = pv_tafe_institute_serv.sort_values(by='dissatisfied', ascending=False)*100
# View results
print(f'\033[1mDETE fraction per career stage:\033[0;0m\n{pv_dete_institute_serv}\n')
print(f'\033[1mTAFE fraction per career stage:\033[0;0m\n{pv_tafe_institute_serv}')
As we can see above, in DETE institute there are more employees are likely to leave from their work even after spending many years. Especially, Established
workers (60%) tend to quit more offten than any other category of DETE. Even in the TAFE institute, it is the same Established
workers (33%) who left their job due to some sort of discontentment. The overall trend shows that the DETE institute fails to satisfy as compared to TAFE.
To conclude our analysis, let's implement the same steps above for age-category.
Let's calculate the age percentage of the dissatisfied employees in each of the institutes.
# Find percentage of the dissatisfied employees based on the age categories
pv_dete_institute_age = dete_institute.pivot_table(index='age_cat', values='dissatisfied')
# Sort the values of 'dissatisfied' column in descending order
pv_dete_institute_age = pv_dete_institute_age.sort_values(by='dissatisfied', ascending=False)*100
# Find percentage of the dissatisfied employees based on the service categories
pv_tafe_institute_age = tafe_institute.pivot_table(index='age_cat', values='dissatisfied')
# Sort the values of 'dissatisfied' column in descending order
pv_tafe_institute_age = pv_tafe_institute_age.sort_values(by='dissatisfied', ascending=False)*100
# View results
print(f'\033[1mDETE fraction per age:\033[0;0m\n{pv_dete_institute_age}\n')
print(f'\033[1mTAFE fraction per age:\033[0;0m\n{pv_tafe_institute_age}')
For the age-categories we see some interesting trend. Seniors have resigned the most due to dissatisfied who worked in the DETE (about 52%), also, adults (51%) and young (45%) follow closely to each other. Teen have no impact on overall percentage. On the other hand, the impact of disconent people in the TAFE is far less than DETE. In TAFE, adults and young people make almost the same results (26%), whereas, young people are tend to quit the job about 22%. It seems like seniors are pretty satisfied working in TAFE, that is why they don't have any contribution in the total results.
It completes our analysis, next we'll visualize our findings.
In this section we'll make presentation of the results in service_cat
and age_cat
, founded in the Exploratory Data Analysis.
Let's visualize the results dissatisfied people in each category and also the patterns in each insitute individually (DETE and TAFE).
# Set graph style
style.use('fivethirtyeight')
# Create figure and axes object
fig, ax = plt.subplots(figsize=(12,8))
# Create bar plot of service-categories of the dissatisfied employees
dis_serv_pv.plot(kind='bar', ax=ax, rot=0, color='#800070', legend=False)
# Change the fontsize of 'major' ticks on both x and y axes
ax.tick_params(axis='both', which='major', labelsize=18)
# Add '%' sign on the y-axis ticks and exclude the last tick (i.e. 60)
ax.yaxis.set_ticks(ticks=ax.get_yticks()[:-1], labels=[ '0 ', '10 ', '20 ', '30 ', '40 ', '50%'])
# Generate a bolded horizontal line at y=0
ax.axhline(y=0, color='black', linewidth=6, alpha=.5)
# Remove the label of the x-axis
ax.xaxis.label.set_visible(False)
# Add labels to the bars
ax.bar_label(ax.containers[0], label_type='edge', fontsize=16, fmt='%.2f')
# Add title and the subtitle
ax.text(x=-0.71, y=62.5, fontsize=26, weight='bold', alpha=0.95,
s='Unhappy Australian employees in different stages of career')
ax.text(x=-0.70, y=54.5, fontsize=19, alpha=0.85, backgroundcolor='#f0f0f0',
s='Percentage of people who resigned due to dissatisfaction in the Queensland department of\neducation from 1963 to 2013 for extreme cases where the percentage is more than 50%\nfor established workers')
# Create the figure and a set of subplots for DETE vs. TAFE
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(12,8))
# Create horizontal bar plot of 'pv_dete_institute_serv'
pv_dete_institute_serv.plot(kind='barh', ax=ax[0], color='#700080', legend=False)
# Remove 'major' and 'minor' ticks y-axis
ax[0].tick_params(axis='y', which='both', labelleft=False)
# Add '%' sign on the x-axis ticks and exclude the last tick (i.e. 70)
ax[0].xaxis.set_ticks(ticks=ax[0].get_xticks()[:-1], labels=['0', '10', '20', '30', '40', '50', '60%'])
# Generate a bolded vertical line at x=0
ax[0].axvline(x=0, color='black', linewidth=5, alpha=.7)
# Remove the label of the y-axis
ax[0].yaxis.label.set_visible(False)
# Add title
ax[0].text(x=1, y=3.5, s='Fraction of dissatisfied people per career stage (DETE)', fontsize=18)
# Add colored labels
ax[0].annotate('New (37%)', # text
xy=(11, 2.5), xycoords='data', # point to annotate
xytext=(-100, 21), textcoords='offset points', # position to place text at
size=14, color='#ffffff')
ax[0].annotate('Experienced (45%)',
xy=(11, 1.5), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
ax[0].annotate('Veteran (51%)',
xy=(11, 0.5), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
ax[0].annotate('Established (61%)',
xy=(11, -0.5), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
# Create horizontal bar plot of 'pv_tafe_institute_serv'
pv_tafe_institute_serv.plot(kind='barh', ax=ax[1], color='#510080', legend=False)
ax[1].tick_params(axis='y', which='both', labelleft=False)
ax[1].xaxis.set_ticks(ticks=ax[1].get_xticks()[:-1], labels=[ '0', '5', '10', '15', '20', '25', '30%'])
ax[1].axvline(x=0, color='black', linewidth=5, alpha=.7)
ax[1].yaxis.label.set_visible(False)
# Add title
ax[1].text(x=0.5, y=3.5, s='Fraction of dissatisfied people per career stage (TAFE)', fontsize=18)
# Add colored labels
ax[1].annotate('Experience (25%)',
xy=(6, 2.5), xycoords='data',
xytext=(-100, 21.5), textcoords='offset points',
size=14, color='#ffffff')
ax[1].annotate('New (26%)',
xy=(6, 1.5), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
ax[1].annotate('Veteran (27%)',
xy=(6, 0.5), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
ax[1].annotate('Established (33%)',
xy=(6, -0.5), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
# The signature bar
ax[1].text(x=-0.5, y=-1.3, color='#f0f0f0', fontsize=14, backgroundcolor='grey',
s=' ©Muhammad Awon' +' '*75 + 'Source: Queensland Department of Education, Australia ')
plt.show()
Now we'll visualize resignation of dissatisfied people based on age category and also draw the age comparision between DETE and TAFE.
# Create figure and axes object
fig, ax = plt.subplots(figsize=(12,10))
# Create bar plot of service-categories of the dissatisfied employees
dis_age_pv.plot(kind='bar', ax=ax, rot=0, color='#800070', legend=False)
# Change the fontsize of 'major' ticks on both x and y axes
ax.tick_params(axis='both', which='major', labelsize=18)
# Add '%' sign on the y-axis ticks and exclude the last tick (i.e. 60)
ax.yaxis.set_ticks(ticks=ax.get_yticks()[:-1], labels=[ '0 ', '10 ', '20 ', '30 ', '40 ', '50%'])
# Generate a bolded horizontal line at y=0
ax.axhline(y=0, color='black', linewidth=6, alpha=.5)
# Remove the label of the x-axis
ax.xaxis.label.set_visible(False)
# Add labels to the bars
ax.bar_label(ax.containers[0], label_type='edge', fontsize=16, fmt='%.2f')
# Add title and the subtitle
ax.text(x=-0.71, y=59, fontsize=26, weight='bold', alpha=0.95,
s='Age stages of unhappy Australian employees')
ax.text(x=-0.70, y=54.5, fontsize=19, alpha=0.85, backgroundcolor='#f0f0f0',
s='The age distribution of the discontent people in the Queensland department of education\nfrom 1963 to 2013 where in extreme the percentage goes over 52% for senior workers')
# Create the figure and a set of subplots for DETE vs. TAFE
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(12,8))
# Create horizontal bar plot of 'pv_dete_institute_age'
pv_dete_institute_age.plot(kind='barh', ax=ax[0], color='#700080', legend=False)
# Remove 'major' and 'minor' ticks on y-axis
ax[0].tick_params(axis='y', which='both', labelleft=False)
# Add '%' sign on the x-axis ticks and exclude the last tick (i.e. 60)
ax[0].xaxis.set_ticks(ticks=ax[0].get_xticks()[:-1], labels=['0', '10', '20', '30', '40', '50%'])
# Generate a bolded vertical line at x=0 (line ymax=0.78)
ax[0].axvline(x=0, ymax=0.78, color='black', linewidth=5, alpha=.7)
# Remove the label of the y-axis
ax[0].yaxis.label.set_visible(False)
# Add title
ax[0].text(x=1, y=2.5, s='Fraction of dissatisfied people per age stage (DETE)', backgroundcolor='#f0f0f0', fontsize=18)
# Add colored labels
ax[0].annotate('Young (45%)',
xy=(9.5, 1.5), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
ax[0].annotate('Adults (51%)',
xy=(9.5, 0.5), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
ax[0].annotate('Senior (52%)',
xy=(9.5, -0.5), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
# Create horizontal bar plot of 'pv_tafe_institute_age'
pv_tafe_institute_age.plot(kind='barh', ax=ax[1], color='#510080', legend=False)
ax[1].tick_params(axis='y', which='both', labelleft=False)
ax[1].xaxis.set_ticks(ticks=ax[1].get_xticks()[:-1], labels=[ '0', '5', '10', '15', '20', '25%'])
ax[1].axvline(x=0, color='black', linewidth=5, alpha=.7)
ax[1].yaxis.label.set_visible(False)
# Add title
ax[1].text(x=0.5, y=2.5, s='Fraction of dissatisfied people per age stage (TAFE)', backgroundcolor='#f0f0f0', fontsize=18)
# Add colored labels
ax[1].annotate('Teen (22%)',
xy=(5, 1.6), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
ax[1].annotate('Young (26%)',
xy=(5, 0.6), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
ax[1].annotate('Adults (27%)',
xy=(5, -0.35), xycoords='data',
xytext=(-100, 21), textcoords='offset points',
size=14, color='#ffffff')
# The signature bar
ax[1].text(x=-0.5, y=-1.1, color='#f0f0f0', fontsize=14, backgroundcolor='grey',
s=' ©Muhammad Awon' +' '*70 + 'Source: Queensland Department of Education, Australia ')
plt.show()
In this project, we've experienced that in order to extract any meaningful insights from our data, we had to perform many data cleaning task. Specifically, we've cleaned the employees exit surveys from 2 Australian institutes, and analyzed the data from the standpoint of relations between resigning from the company because of some kind of dissatisfaction and the age or the length of service. As a result, we can conclude the following: