Skip to content

Your client, SleepInc, has shared anonymized sleep data from their hot new sleep tracking app SleepScope. As their data science consultant, your mission is to analyze the lifestyle survey data with Python to discover relationships between exercise, gender, occupation, and sleep quality. See if you can identify patterns leading to insights on sleep quality.

💾 The data: sleep_health_data.csv

SleepInc has provided you with an anonymized dataset of sleep and lifestyle metrics for 374 individuals. This dataset contains average values for each person calculated over the past six months. The data is saved as sleep_health_data.csv.

The dataset includes 13 columns covering sleep duration, quality, disorders, exercise, stress, diet, demographics, and other factors related to sleep health.

ColumnDescription
Person IDAn identifier for each individual.
GenderThe gender of the person (Male/Female).
AgeThe age of the person in years.
OccupationThe occupation or profession of the person.
Sleep Duration (hours)The average number of hours the person sleeps per day.
Quality of Sleep (scale: 1-10)A subjective rating of the quality of sleep, ranging from 1 to 10.
Physical Activity Level (minutes/day)The average number of minutes the person engages in physical activity daily.
Stress Level (scale: 1-10)A subjective rating of the stress level experienced by the person, ranging from 1 to 10.
BMI CategoryThe BMI category of the person (e.g., Underweight, Normal, Overweight).
Blood Pressure (systolic/diastolic)The average blood pressure measurement of the person, indicated as systolic pressure over diastolic pressure.
Heart Rate (bpm)The average resting heart rate of the person in beats per minute.
Daily StepsThe average number of steps the person takes per day.
Sleep DisorderThe presence or absence of a sleep disorder in the person (None, Insomnia, Sleep Apnea).
# Start coding here
# Use as many cells as you need
import pandas as pd


df=pd.read_csv("sleep_health_data.csv")

df.head()
# Summary statistics
print(df.describe())

# Check for missing values
print(df.isnull().sum())

# Data types of columns
print(df.dtypes)
# Grouping the data by occupation and calculating the mean sleep duration
occupation_sleep_duration = df.groupby('Occupation')['Sleep Duration'].mean()

# Finding the occupation with the lowest sleep duration
occupation_lowest_sleep_duration = occupation_sleep_duration.idxmin()
lowest_sleep_duration = occupation_sleep_duration.min()

print(f"Occupation with the lowest sleep duration: {occupation_lowest_sleep_duration}")
print(f"Average sleep duration: {lowest_sleep_duration} hours")

import matplotlib.pyplot as plt

# Plotting the mean sleep duration by occupation
plt.figure(figsize=(12, 6))
occupation_sleep_duration.plot(kind='bar', color='skyblue')
plt.title('Mean Sleep Duration by Occupation')
plt.xlabel('Occupation')
plt.ylabel('Mean Sleep Duration (hours)')
plt.xticks(rotation=45, ha='right')
plt.tight_layout()

# Highlighting the occupation with the lowest sleep duration
plt.axhline(y=lowest_sleep_duration, color='r', linestyle='--', label=f'Lowest: {occupation_lowest_sleep_duration} ({lowest_sleep_duration} hours)')
plt.legend()

plt.show()
# Grouping the data by occupation and calculating the mean sleep quality
occupation_sleep_quality = df.groupby('Occupation')['Quality of Sleep'].mean()

# Finding the occupation with the lowest sleep quality
occupation_lowest_sleep_quality = occupation_sleep_quality.idxmin()
lowest_sleep_quality = occupation_sleep_quality.min()

print(f"Occupation with the lowest sleep quality: {occupation_lowest_sleep_quality}")
print(f"Average sleep quality: {lowest_sleep_quality}")

import matplotlib.pyplot as plt
# Grouping the data by occupation and calculating the mean sleep quality
occupation_sleep_quality = df.groupby('Occupation')['Quality of Sleep'].mean()
# Plotting the mean sleep quality by occupation
plt.figure(figsize=(10, 6))
occupation_sleep_quality.plot(kind='bar', color='pink')
plt.title('Mean Sleep Quality by Occupation')
plt.xlabel('Occupation')
plt.ylabel('Mean Quality of Sleep')
plt.xticks(rotation=45)
plt.show()
# Grouping the data by BMI category and sleep disorder
bmi_sleep_disorder = df.groupby(['BMI Category', 'Sleep Disorder']).size()

# Extracting counts of users diagnosed with Insomnia by BMI category
insomnia_counts = bmi_sleep_disorder.loc[:, 'Insomnia']

# Calculating total counts of users by BMI category
total_counts = bmi_sleep_disorder.sum(level='BMI Category')

# Calculating the ratio of app users diagnosed with Insomnia in each BMI category
insomnia_ratio = insomnia_counts / total_counts

print("Ratio of app users diagnosed with Insomnia in each BMI category:")
print(insomnia_ratio)

import matplotlib.pyplot as plt
# Plotting the ratio of app users diagnosed with Insomnia in each BMI category
insomnia_ratio.plot(kind='bar', color='pink', edgecolor='grey')
# Adding title and labels
plt.title('Ratio of App Users Diagnosed with Insomnia by BMI Category')
plt.xlabel('BMI Category')
plt.ylabel('Ratio of Users with Insomnia')
# Displaying the plot
plt.show()
# Grouping the data by occupation and calculating the mean sleep duration
occupation_sleep_duration = df.groupby('Occupation')['Sleep Duration'].mean()

# Finding the occupation with the lowest sleep duration
lowest_sleep_occ = occupation_sleep_duration.idxmin()

print(f"Occupation with the lowest sleep duration: {lowest_sleep_occ}")
# Grouping the data by occupation and calculating the mean sleep quality
occupation_sleep_quality = df.groupby('Occupation')['Quality of Sleep'].mean()

# Finding the occupation with the lowest sleep quality
lowest_sleep_quality_occ = occupation_sleep_quality.idxmin()

# Check if the occupation with the lowest sleep duration is the same as the one with the lowest sleep quality
same_occ = lowest_sleep_occ == lowest_sleep_quality_occ

print(f"Occupation with the lowest sleep quality: {lowest_sleep_quality_occ}")

print(f"Did the occupation with the lowest sleep duration also have the lowest sleep quality? {same_occ}")
# Grouping the data by BMI category and sleep disorder
bmi_sleep_disorder = df.groupby(['BMI Category', 'Sleep Disorder']).size()

# Extracting counts of users diagnosed with Insomnia by BMI category
insomnia_counts = bmi_sleep_disorder.loc[:, 'Insomnia']

# Calculating total counts of users by BMI category
total_counts = bmi_sleep_disorder.sum(level='BMI Category')

# Calculating the ratio of app users diagnosed with Insomnia in each BMI category
insomnia_ratio = insomnia_counts / total_counts

# Converting the ratio to a dictionary with rounded values
bmi_insomnia_ratios = {str(bmi_category): round(insomnia_ratio[bmi_category], 2) for bmi_category in insomnia_ratio.index.get_level_values('BMI Category').unique()}

print("Ratio of app users diagnosed with Insomnia in each BMI category:")
print(bmi_insomnia_ratios)