Exploratory Data Analysis of Patient Demographics and Disease Trends

Introduction

This project focuses on analyzing a healthcare dataset containing 8,000 patient records to uncover insights into patient demographics, disease prevalence, and treatment patterns. By leveraging Python and data visualization techniques, the analysis explores how patient populations are distributed by gender, how age groups vary across admissions, and which diseases are most commonly diagnosed. Using Pandas for data processing and Matplotlib and Seaborn for visualization, the project provides a clear representation of key trends within the dataset. The findings highlight important patterns, such as the distribution of male and female patients, the most affected age groups, and the top three diagnosed diseases. These insights can be valuable for hospital management, medical research, and public health decision-making.

πŸ”₯ GitHub Repository

1. Health Dataset Analysis

This project involves analyzing a health dataset to assess various health indicators and metrics. The dataset contains patient records, and the goal is to process and analyze the data to provide insights into the health status of the population. The analysis includes counting the total number of patient records and previewing the data to ensure that it’s ready for further exploration.


import pandas as pd
import os

# Define the file path
file_path = r"C:\Users\user\Downloads\Python Project\Health Dataset Python\Health Dataset Python\Health_dataset.csv"

# Check if the file exists before proceeding
if os.path.exists(file_path):
    # Load data from CSV
    health_data = pd.read_csv(file_path)

# Import matplotlib and seaborn    
import matplotlib.pyplot as plt
import seaborn as sns

    # Display the first few rows
    print("First 5 rows of the dataset:")
    print(health_data.head())

    # Count the number of patients (records)
    total_records = health_data.shape[0]

    # Print the total number of patients
    print(f"Total Patients: {total_records}")
else:
    print("Error: File not found. Please check the file path.")
    

πŸ“Š Data Insights & Interpretation

This analysis provides an overview of the health dataset, including the number of patient records and the first few rows for inspection. By counting the total number of patients, we gain an understanding of the scope of the dataset.

  • βœ… The dataset contains a total of {total_records} patient records.
  • βœ… The first few rows of the dataset provide a preview of the health metrics, which include various patient attributes such as age, gender, and medical history.
  • πŸ“Œ Further analysis can help identify trends, patterns, and correlations between different health metrics.

This initial analysis sets the stage for more in-depth exploration of the health dataset, potentially identifying correlations between patient attributes and health outcomes. πŸš€πŸ“Š

2. Patient Population Distribution by Gender

This analysis explores how the patient population is distributed by gender. Understanding the gender distribution within a healthcare dataset can provide insights into potential trends or disparities in healthcare outcomes between male and female patients.


# How is the patient population distributed by gender?
gender_count = health_data['Gender'].value_counts()

print("\nPatient Population Distribution by Gender:")
for gender, count in gender_count.items():
    print(f"{gender}: {count} patients")
    
Gender Number of Patients
Male 5206
Female 2794

πŸ“Š Data Insights & Interpretation

The patient population is distributed as follows:

  • βœ… 5206 male patients represent a significant portion of the dataset.
  • βœ… 2794 female patients are also part of the dataset, showing a noticeable difference in gender distribution.
  • πŸ“Œ Further investigation could explore whether gender influences health outcomes or treatment responses.

This distribution provides a foundational understanding of the gender composition in the dataset and sets the stage for further analyses, such as gender-based health outcome comparisons. πŸš€πŸ“Š

3. Visualizing Patient Population Distribution by Gender

To better understand the gender distribution among patients, a bar chart was created. Visualizing data helps identify trends and disparities more effectively than raw numbers alone.



# How is the patient population distributed by gender?
gender_count = health_data['Gender'].value_counts()

# Set the style for the plot
sns.set_style("whitegrid")

# Define custom colors
custom_colors = ["skyblue", "lightgreen"]

# Create a bar plot
plt.figure(figsize=(8, 5))
ax = sns.barplot(x=gender_count.index, y=gender_count.values, palette=custom_colors)

# Add labels and title
plt.xlabel("Gender")
plt.ylabel("Number of Patients")
plt.title("Patient Population Distribution by Gender")
plt.xticks(rotation=0)  # Keep labels horizontal

# Annotate bars with the total number of patients
for i, count in enumerate(gender_count.values):
    ax.text(i, count + 5, str(count), ha='center', color='black', fontsize=12)

# Save the plot as an image
plt.savefig("images/gender_distribution.png", dpi=300, bbox_inches='tight')

plt.show()
    
Bar chart showing patient population distribution by gender

πŸ“Š Data Insights & Interpretation

This bar chart provides a clear visual representation of the gender distribution among patients:

  • βœ… Male patients are significantly more than female patients.
  • βœ… The visualization helps identify any noticeable disparities in gender representation.
  • πŸ“Œ Further analysis can explore whether gender distribution impacts health conditions or treatment responses.

By using data visualization, we can gain deeper insights into the dataset, making it easier to interpret trends and patterns. πŸ“ŠπŸ“ˆ

4. Visualizing Patient Population Distribution (Pie Chart)

To further analyze the gender distribution among patients, a pie chart was created. This visualization helps in understanding the proportion of male and female patients in the dataset.



# Create a pie chart
plt.figure(figsize=(6, 6))
plt.pie(gender_count, labels=gender_count.index, autopct='%1.1f%%', 
        colors=["skyblue", "lightgreen"], startangle=90)
plt.title("Patient Population Distribution by Gender")

# Save the pie chart as an image
plt.savefig("images/gender_distribution_pie.png", dpi=300, bbox_inches='tight')

plt.show()
    
Pie chart showing patient population distribution by gender

πŸ“Š Data Insights & Interpretation

The pie chart provides a quick and intuitive way to compare the proportions of male and female patients:

  • βœ… The chart highlights the dominant gender group in the patient population.
  • βœ… It allows for an easy percentage-based comparison between male and female patients.
  • πŸ“Œ Further investigation can explore how gender distribution relates to specific health conditions or treatments.

This visualization enhances our understanding of demographic patterns in healthcare data, providing actionable insights for decision-making. πŸ“ŠπŸ•

5. Categorizing Patients by Age Group

Understanding the age distribution of patients is essential for healthcare analysis. This process involves calculating patients' ages based on their Admission Date and Date of Birth and categorizing them into predefined age groups.


# Convert columns to datetime
health_data['Admission Date'] = pd.to_datetime(health_data['Admission Date'])
health_data['Date of Birth'] = pd.to_datetime(health_data['Date of Birth'])

# Calculate Age
health_data['Age'] = (health_data['Admission Date'] - health_data['Date of Birth']).dt.days // 365

# Define Age Bins and Labels
age_bins = [0, 20, 40, 60, 80, 100, 200]  # Extended upper limit to 200
age_labels = ["0-20", "21-40", "41-60", "61-80", "81-100", "100+"]

# Categorize patients into Age Groups
health_data['Age Group'] = pd.cut(health_data['Age'], bins=age_bins, labels=age_labels, 
                                  right=True, include_lowest=True)

# Check if all patients are categorized
missing_age_group = health_data['Age Group'].isna().sum()
print(f"Patients without an Age Group: {missing_age_group}")

# Display count of patients in each age group
age_group_counts = health_data['Age Group'].value_counts()
print(age_group_counts)
    
Age Group Number of Patients
0-20 1,627
21-40 1,618
41-60 1,609
61-80 1,587
81-100 1,559
100+ 0

πŸ“Š Data Insights & Interpretation

Categorizing patients into age groups helps in identifying key demographic trends in healthcare:

  • βœ… The 0-20 age group has the highest number of patients (1,627).
  • βœ… Patient numbers are fairly consistent across all age groups, with a slight decrease in older groups.
  • πŸ“Œ No patients fall into the 100+ age group, indicating a possible cutoff in dataset records.

This age categorization aids in medical research, hospital planning, and targeted healthcare strategies. πŸ“ŠπŸ“…

6. Patient Distribution by Age Group

To analyze the age distribution of patients, we calculated their age at admission and grouped them into predefined age categories. The resulting visualization helps in identifying trends in patient demographics.



# Convert columns to datetime
health_data['Admission Date'] = pd.to_datetime(health_data['Admission Date'])
health_data['Date of Birth'] = pd.to_datetime(health_data['Date of Birth'])

# Calculate Age at Admission
health_data['Age'] = (health_data['Admission Date'] - health_data['Date of Birth']).dt.days // 365

# Define Age Bins and Labels (Upper limit set to 200)
age_bins = [0, 20, 40, 60, 80, 100, 200]
age_labels = ["0-20", "21-40", "41-60", "61-80", "81-100", "100+"]

# Categorize patients into Age Groups
health_data['Age Group'] = pd.cut(health_data['Age'], bins=age_bins, labels=age_labels, 
                                  right=True, include_lowest=True)

# Count number of patients in each age group
age_group_counts = health_data['Age Group'].value_counts().sort_index()

# Plotting the bar chart
plt.figure(figsize=(10, 6))
sns.barplot(x=age_group_counts.index, y=age_group_counts.values, 
            palette=['skyblue', 'lightgreen', 'lightcoral', 'lightskyblue', 'lightpink', 'lightyellow'])

# Adding chart labels and title
plt.title('Patient Distribution by Age Group', fontsize=16)
plt.xlabel('Age Group', fontsize=14)
plt.ylabel('Number of Patients', fontsize=14)

# Display total count of patients in each age group on top of bars
for i, v in enumerate(age_group_counts.values):
    plt.text(i, v + 50, str(v), ha='center', fontsize=12)

# Show the plot
plt.show()
    
Patient Distribution by Age Group

πŸ“Š Data Insights & Interpretation

The bar chart presents a clear visualization of the number of patients in each age group:

  • βœ… The 0-20 age group has the highest number of patients.
  • βœ… Patient distribution remains fairly even across most age groups, with a gradual decline in older groups.
  • πŸ“Œ No patients are recorded in the 100+ age group, possibly indicating a dataset limitation.

This visualization helps in demographic analysis and can assist healthcare facilities in planning resources effectively. πŸ“ˆπŸ₯

7. Top 3 Most Diagnosed Diseases Among Patients

Identifying the most commonly diagnosed diseases helps in healthcare resource allocation, treatment planning, and preventive care strategies. This analysis highlights the top 3 diseases affecting patients based on the dataset.


# Which diseases are most commonly diagnosed among patients (Top 3)?

# Check the top 3 most diagnosed diseases
top_3_diseases = health_data['Disease'].value_counts().head(3)

# Display the result
print("Top 3 Diseases Diagnosed:")
print(top_3_diseases)
    

πŸ“‹ Top 3 Most Diagnosed Diseases

Disease Number of Cases
Malaria 1,193 cases
Asthma 966 cases
Tuberculosis 864 cases

πŸ“Š Data Insights & Interpretation

The analysis reveals the top 3 most diagnosed diseases among patients:

  • βœ… Malaria is the most common diagnosis, affecting 1,193 patients.
  • βœ… Asthma follows with 966 cases, indicating respiratory health concerns.
  • βœ… Tuberculosis ranks third with 864 cases, highlighting a need for infectious disease management.
  • πŸ“Œ The prevalence of these diseases suggests a focus on preventive healthcare measures and targeted interventions.

By identifying common diagnoses, healthcare providers can enhance patient care and develop effective treatment strategies. πŸ₯πŸ“ˆ

8. Visualizing the Top 3 Most Diagnosed Diseases

To better understand the most commonly diagnosed diseases among patients, a bar chart was created. Visualizing this data helps in identifying trends and allocating medical resources effectively.



# Identify the top 3 most diagnosed diseases
top_3_diseases = health_data['Disease'].value_counts().head(3)

# Plotting the bar chart
plt.figure(figsize=(8, 5))
sns.barplot(x=top_3_diseases.index, y=top_3_diseases.values, palette='muted')

# Adding chart labels and title
plt.title('Top 3 Most Diagnosed Diseases', fontsize=16)
plt.xlabel('Disease', fontsize=14)
plt.ylabel('Number of Patients Diagnosed', fontsize=14)

# Display total count of patients on top of bars
for i, v in enumerate(top_3_diseases.values):
    plt.text(i, v + 50, str(v), ha='center', fontsize=12)

# Show the plot
plt.show()
    

πŸ“Š Bar Chart: Top 3 Most Diagnosed Diseases

Top 3 Most Diagnosed Diseases Bar Chart

πŸ“Š Data Insights & Interpretation

The bar chart provides a clear visual representation of the top 3 diseases diagnosed:

  • βœ… Malaria is the most common disease, affecting 1,193 patients.
  • βœ… Asthma follows with 966 cases, highlighting respiratory health concerns.
  • βœ… Tuberculosis ranks third with 864 cases, indicating a need for infectious disease control.
  • πŸ“Œ This visualization helps in understanding disease prevalence and guiding public health interventions.

Using data visualization, we can quickly identify which diseases require more medical attention and resources. πŸ“ŠπŸ₯

9. Top 3 Most Diagnosed Diseases (Relative Percentage Analysis)

This analysis examines the top 3 most diagnosed diseases and their relative percentage in the dataset. Understanding the distribution of diseases helps in effective medical resource allocation and health policy planning.


# Identify the top 3 most diagnosed diseases
top_3_diseases = health_data['Disease'].value_counts().head(3)

# Calculate the total number of patients diagnosed with the top 3 diseases
total_top_3 = top_3_diseases.sum()

# Calculate the percentage relative to the top 3 total
top_3_percentages_relative = np.round((top_3_diseases / total_top_3) * 100).astype(int)

# Adjust for rounding to ensure the total is exactly 100%
difference = 100 - top_3_percentages_relative.sum()
top_3_percentages_relative.iloc[0] += difference  # Adjust the largest category

# Combine count and percentage
top_3_summary_relative = pd.DataFrame({'Count': top_3_diseases, 'Percentage': top_3_percentages_relative.astype(str) + "%"})

# Display the total number of patients diagnosed with the top 3 diseases
print(f"Total number of patients diagnosed with the top 3 diseases: {total_top_3:,}")

# Display the formatted summary table
print("\nTop 3 Diseases with Counts and Percentages (Relative to Top 3 Total):")
print(top_3_summary_relative)

# Plotting the bar chart for top 3 diseases
plt.figure(figsize=(8, 5))
sns.barplot(x=top_3_diseases.index, y=top_3_diseases.values, palette='muted')

# Adding chart labels and title
plt.title('Top 3 Most Diagnosed Diseases (Relative %)', fontsize=16)
plt.xlabel('Disease', fontsize=14)
plt.ylabel('Number of Patients Diagnosed', fontsize=14)

# Display total count and percentage on top of bars
for i, (count, percentage) in enumerate(zip(top_3_diseases.values, top_3_percentages_relative.values)):
    plt.text(i, count + 50, f"{count:,} ({percentage}%)", ha='center', fontsize=12)

# Show the plot
plt.show()
    

πŸ“Š Summary: Patient Diagnosis Breakdown

A total of 3,023 patients were diagnosed with the top 3 diseases. Below is the percentage breakdown:

Disease Number of Patients Percentage
Malaria 1,193 39%
Asthma 966 32%
Tuberculosis 864 29%

πŸ“Š Bar Chart: Top 3 Most Diagnosed Diseases (Relative %)

Top 3 Most Diagnosed Diseases Relative Percentage Chart

πŸ“Œ Key Insights

  • βœ… Malaria is the leading diagnosed disease, accounting for 39% of the top 3 cases.
  • βœ… Asthma contributes 32%, showing a high prevalence of respiratory conditions.
  • βœ… Tuberculosis accounts for 29%, indicating a significant number of infectious disease cases.
  • πŸ“Œ This analysis helps in disease prevention planning and targeted healthcare interventions.

10. Gender-Based Disease Prevalence Analysis

This analysis explores whether certain diseases are more prevalent in one gender than the other. Understanding gender-based disease distribution helps in targeted healthcare interventions and personalized treatments.


# Define the number of top diseases to extract
top_n = 5  # Change this value to get top N diseases (e.g., top 10, top 15, etc.)

# Filter dataset by gender
male_diseases = health_data[health_data['Gender'] == 'Male']['Disease'].value_counts().head(top_n)
female_diseases = health_data[health_data['Gender'] == 'Female']['Disease'].value_counts().head(top_n)

# Display top diseases for each gender
print(f"Top {top_n} Diseases Among Males:\n{male_diseases}\n")
print(f"Top {top_n} Diseases Among Females:\n{female_diseases}\n")

# Plot the bar chart
fig, axes = plt.subplots(1, 2, figsize=(14, 5))

# Male Diseases Chart
sns.barplot(x=male_diseases.values, y=male_diseases.index, palette='Blues_r', ax=axes[0])
axes[0].set_title(f"Top {top_n} Diseases Among Males", fontsize=14)
axes[0].set_xlabel("Number of Patients", fontsize=12)
axes[0].set_ylabel("Disease", fontsize=12)

# Female Diseases Chart
sns.barplot(x=female_diseases.values, y=female_diseases.index, palette='Reds_r', ax=axes[1])
axes[1].set_title(f"Top {top_n} Diseases Among Females", fontsize=14)
axes[1].set_xlabel("Number of Patients", fontsize=12)
axes[1].set_ylabel("Disease", fontsize=12)

# Adjust layout and show the plot
plt.tight_layout()
plt.show()
    

πŸ“Š Summary: Gender-Based Disease Breakdown

The top 5 diseases diagnosed among males and females in the dataset are as follows:

πŸ‘¨ Top 5 Diseases Among Males

Disease Number of Patients
Malaria 786
Asthma 646
Tuberculosis 562
Cancer 452
Typhoid 441

πŸ‘© Top 5 Diseases Among Females

Disease Number of Patients
Malaria 407
Asthma 320
Tuberculosis 302
Diabetes 256
Cancer 239

πŸ“Š Visualization: Top 5 Diseases by Gender

Top 5 Diseases Among Males

πŸ“Œ Key Insights

  • βœ… Malaria, Asthma, and Tuberculosis are the top 3 diseases for both genders.
  • βœ… Males have higher cases of Cancer and Typhoid, whereas females have higher cases of Diabetes and Cancer.
  • πŸ“Œ This analysis supports gender-specific healthcare planning and disease prevention strategies.

11. Patient Stay Duration Analysis

This analysis examines the length of hospital stay (LOS) of patients based on admission and discharge dates. Understanding patient stay distribution is essential for hospital resource planning and patient flow management.


# Convert columns to datetime format
health_data['Admission Date'] = pd.to_datetime(health_data['Admission Date'], errors='coerce')
health_data['Discharge Date'] = pd.to_datetime(health_data['Discharge Date'], errors='coerce')

# Calculate Length of Stay (LOS) in days
health_data['Length of Stay'] = (health_data['Discharge Date'] - health_data['Admission Date']).dt.days

# Define stay duration categories
bins = [-1, 0, 3, 7, 14, 21, float('inf')]
labels = ['Same Day', '1-3 Days', '4-7 Days', '8-14 Days', '15-21 Days', 'Above 21 Days']

# Categorize patients based on length of stay
health_data['Stay Category'] = pd.cut(health_data['Length of Stay'], bins=bins, labels=labels, right=True)

# Count patients in each stay category
stay_distribution = health_data['Stay Category'].value_counts().sort_index()

# Display results
print("Patient Stay Distribution:\n")
print(stay_distribution)

# Create a bar chart
plt.figure(figsize=(10, 5))
sns.barplot(x=stay_distribution.index, y=stay_distribution.values, palette="coolwarm")

# Add labels and title
plt.xlabel("Length of Stay Category", fontsize=12)
plt.ylabel("Number of Patients", fontsize=12)
plt.title("Patient Stay Duration Distribution", fontsize=14)

# Display the values on the bars
for index, value in enumerate(stay_distribution.values):
    plt.text(index, value + 50, f"{value:,}", ha='center', fontsize=10, fontweight='bold')

# Show the plot
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
    

πŸ“Š Summary: Patient Stay Distribution

The distribution of patient stays across different categories is as follows:

Stay Category Number of Patients
Same Day 0
1-3 Days 807
4-7 Days 1,087
8-14 Days 1,837
15-21 Days 1,855
Above 21 Days 2,414

πŸ“Š Visualization: Patient Stay Duration

Patient Stay Duration Distribution

πŸ“Œ Key Insights

  • βœ… Most patients (2,414) stayed for over 21 days, indicating a significant number of long-term patients, possibly due to complex conditions or treatments.
  • βœ… The 4-7 day and 8-14 day categories also have substantial numbers, with 1,087 and 1,837 patients, respectively.
  • πŸ“Œ Hospital resource planning should account for these extended stays, ensuring capacity for long-term care needs.

12. Top Causes of Death Analysis

This analysis investigates the most common causes of death among patients. Identifying top causes of death is crucial for improving healthcare interventions and developing targeted prevention strategies.


# Remove blank (NaN) values in "Cause of Death" column
health_data = health_data.dropna(subset=['Cause of Death'])

# Function to get the top N causes of death
def top_causes_of_death(n=5):
    # Count occurrences of each cause of death
    death_counts = health_data['Cause of Death'].value_counts().head(n)

    # Display results
    print(f"\nTop {n} Causes of Death:\n")
    print(death_counts.to_string())

    # Create a bar chart
    plt.figure(figsize=(10, 5))
    sns.barplot(x=death_counts.index, y=death_counts.values, palette="Reds_r")

    # Add labels and title
    plt.xlabel("Cause of Death", fontsize=12)
    plt.ylabel("Number of Patients", fontsize=12)
    plt.title(f"Top {n} Most Common Causes of Death", fontsize=14)

    # Display values on the bars
    for index, value in enumerate(death_counts.values):
        plt.text(index, value + 5, f"{value:,}", ha='center', fontsize=10, fontweight='bold')

    # Show the plot
    plt.xticks(rotation=45, ha='right')
    plt.tight_layout()
    plt.show()

# Call the function (Change the number as needed)
top_causes_of_death(n=5)  # Change "5" to any number (e.g., 10, 15, etc.)
    

πŸ“Š Summary: Top Causes of Death

The top 5 causes of death based on the number of occurrences are:

Cause of Death Number of Patients
Multiple Organ Failure 114
Respiratory Failure 109
Cardiac Arrest 102
Septic Shock 94

πŸ“Š Visualization: Top Causes of Death

Top Causes of Death

πŸ“Œ Key Insights

  • βœ… The most common cause of death is Multiple Organ Failure (114 patients), followed closely by Respiratory Failure (109 patients).
  • βœ… Cardiac Arrest (102 patients) and Septic Shock (94 patients) are also among the top contributors.
  • πŸ“Œ These results highlight critical areas where preventive healthcare measures could be focused, especially for patients with comorbidities.

13. Treatment Status Distribution

This analysis presents the distribution of treatment status among patients, highlighting the proportion of patients who have recovered, are under treatment, or are deceased. This breakdown is crucial for understanding patient outcomes and the effectiveness of treatments.


# Count occurrences of each Treatment Status
treatment_counts = health_data['Treatment Status'].value_counts()

# Total number of patients
total_patients = treatment_counts.sum()

# Calculate percentage for each category
treatment_percentages = (treatment_counts / total_patients) * 100

# Round percentages and add "%" symbol
treatment_summary = pd.DataFrame({
    'Count': treatment_counts,
    'Percentage': treatment_percentages.round(2).astype(str) + "%"
})

# Display the results
print("\nTreatment Status Distribution:")
print(treatment_summary.to_string())
    

πŸ“Š Summary: Treatment Status Distribution

The distribution of treatment status is as follows:

Treatment Status Count Percentage
Recovered 6819 85.24%
Under Treatment 762 9.52%
Deceased 419 5.24%

πŸ“Œ Key Insights

  • βœ… A significant proportion of patients, 85.24%, have recovered from their conditions.
  • βœ… 9.52% of patients are still under treatment, with 5.24% having unfortunately deceased.
  • πŸ“Š This data is essential for assessing the success of treatment protocols and identifying areas of concern for further research.

14. Treatment Status Distribution (Doughnut Chart)

This doughnut chart visually represents the distribution of patients across various treatment statuses. The chart highlights the proportion of patients who have recovered, are under treatment, and those who have deceased.


# Count occurrences of each Treatment Status
treatment_counts = health_data['Treatment Status'].value_counts()

# Total number of patients
total_patients = treatment_counts.sum()

# Calculate percentage for each category
treatment_percentages = (treatment_counts / total_patients) * 100

# Create a Doughnut chart
plt.figure(figsize=(8, 8))

# Plot a pie chart
plt.pie(treatment_percentages, labels=treatment_percentages.index, autopct='%1.1f%%', startangle=90, colors=['#66b3ff', '#99ff99', '#ff6666'])

# Draw a circle at the center to make it a doughnut chart
centre_circle = plt.Circle((0, 0), 0.50, color='white', fc='white', linewidth=1.25)
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

# Equal aspect ratio ensures that pie is drawn as a circle
plt.axis('equal')  
plt.title('Treatment Status Distribution', fontsize=14)

# Show the plot
plt.tight_layout()
plt.show()
    

πŸ“Š Summary: Treatment Status Distribution

The doughnut chart below represents the distribution of treatment statuses across the patient dataset:

Treatment Status Doughnut Chart

πŸ“Œ Key Insights

  • βœ… 85.24% of patients have recovered, making this the largest group.
  • βœ… 9.52% of patients are under treatment, still in care.
  • βœ… 5.24% of patients have unfortunately deceased.
  • πŸ“Š The doughnut chart provides a clear visual representation, showing the relative proportions of each treatment status.

15. Admission Heatmap Analysis: Trends by Day & Month

This heatmap visualizes patient admission trends across different days of the week and months of the year. The analysis helps identify patterns in hospital admissions, such as peak admission days and seasonal trends.



# Convert Admission Date and Discharge Date to datetime format
health_data['Admission Date'] = pd.to_datetime(health_data['Admission Date'], errors='coerce')
health_data['Discharge Date'] = pd.to_datetime(health_data['Discharge Date'], errors='coerce')

# Extract Admission Day of the Week and Month
health_data['Admission Day'] = health_data['Admission Date'].dt.day_name()
health_data['Admission Month'] = health_data['Admission Date'].dt.month_name()

# Create a pivot table for the heatmap
pivot_table = health_data.pivot_table(index='Admission Day', columns='Admission Month', aggfunc='size', fill_value=0)

# Sort days of the week in order
day_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
pivot_table = pivot_table.reindex(day_order)

# Sort months in calendar order from January to December
month_order = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
pivot_table = pivot_table[month_order]

# Plot the heatmap
plt.figure(figsize=(12, 8))
sns.heatmap(pivot_table, annot=True, cmap='YlGnBu', linewidths=0.5, linecolor='gray', fmt='d')
plt.title('Heatmap of Admissions by Day of the Week and Month', fontsize=14)
plt.xlabel('Admission Month')
plt.ylabel('Admission Day')
plt.xticks(rotation=45)
plt.yticks(rotation=0)
plt.tight_layout()
plt.show()
    

πŸ“Š Summary: Admission Trends Heatmap

The heatmap below illustrates the frequency of patient admissions by day of the week and month of the year:

Admission Heatmap

πŸ“Œ Key Insights

  • βœ… Peak Admissions occur on specific days of the week, which can help with hospital resource planning.
  • βœ… Seasonal Trends: Admissions may vary across different months due to seasonal diseases, flu outbreaks, or environmental factors.
  • βœ… The heatmap provides a visual representation of busy periods, aiding in staffing and operational efficiency.