help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
healthcare-patients
RSK World
healthcare-patients
Healthcare Patients Dataset - Medical Analytics + Healthcare Data Science + Patient Data Analysis
healthcare-patients
  • visualizations
  • .gitignore785 B
  • ADVANCED_FEATURES.md5.8 KB
  • FILES_SUMMARY.md2.8 KB
  • GITHUB_PUSH_SUMMARY.md3.4 KB
  • IMAGE_DESCRIPTION.md1.6 KB
  • LICENSE1.2 KB
  • PROJECT_INFO.md2.2 KB
  • PROJECT_SUMMARY.md5.7 KB
  • QUICKSTART.md1.7 KB
  • README.md5.4 KB
  • RELEASE_NOTES.md7.4 KB
  • advanced_analysis.py13.7 KB
  • advanced_analysis_report.txt2.3 KB
  • analyze_patients.py13.8 KB
  • export_to_excel.py6 KB
  • export_to_json.py3.5 KB
  • healthcare_patients.csv6.5 KB
  • healthcare_patients.json27.2 KB
  • healthcare_patients.xlsx14.6 KB
  • index.html26 KB
  • requirements.txt578 B
  • validate_data.py6 KB
analyze_patients.py
analyze_patients.py
Raw Download
Find: Go to:
"""
Healthcare Patient Dataset Analysis Script
==========================================
This script performs comprehensive analysis on the healthcare patient dataset
including statistical analysis, data visualization, and predictive insights.

Author: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')

# Set style for better visualizations
sns.set_style("whitegrid")
plt.rcParams['figure.figsize'] = (12, 6)

def load_data(file_path='healthcare_patients.csv'):
    """
    Load the healthcare patient dataset from CSV file.
    
    Parameters:
    file_path (str): Path to the CSV file
    
    Returns:
    pd.DataFrame: Loaded dataset
    """
    try:
        df = pd.read_csv(file_path)
        # Convert date columns to datetime
        df['admission_date'] = pd.to_datetime(df['admission_date'])
        df['discharge_date'] = pd.to_datetime(df['discharge_date'])
        print(f"✓ Dataset loaded successfully: {len(df)} patients")
        return df
    except FileNotFoundError:
        print(f"✗ Error: File '{file_path}' not found")
        return None
    except Exception as e:
        print(f"✗ Error loading data: {str(e)}")
        return None

def basic_statistics(df):
    """
    Display basic statistical information about the dataset.
    
    Parameters:
    df (pd.DataFrame): Patient dataset
    """
    print("\n" + "="*60)
    print("BASIC STATISTICS")
    print("="*60)
    
    print(f"\nTotal Patients: {len(df)}")
    print(f"Total Features: {len(df.columns)}")
    print(f"\nDataset Shape: {df.shape}")
    
    print("\n--- Age Statistics ---")
    print(f"Mean Age: {df['age'].mean():.2f} years")
    print(f"Median Age: {df['age'].median():.2f} years")
    print(f"Age Range: {df['age'].min()} - {df['age'].max()} years")
    print(f"Standard Deviation: {df['age'].std():.2f}")
    
    print("\n--- Gender Distribution ---")
    print(df['gender'].value_counts())
    
    print("\n--- Blood Type Distribution ---")
    print(df['blood_type'].value_counts())
    
    print("\n--- Length of Stay Statistics ---")
    print(f"Mean Length of Stay: {df['length_of_stay'].mean():.2f} days")
    print(f"Median Length of Stay: {df['length_of_stay'].median():.2f} days")
    print(f"Min Length of Stay: {df['length_of_stay'].min()} days")
    print(f"Max Length of Stay: {df['length_of_stay'].max()} days")
    
    print("\n--- Charges Statistics ---")
    print(f"Mean Charges: ${df['charges'].mean():,.2f}")
    print(f"Median Charges: ${df['charges'].median():,.2f}")
    print(f"Total Charges: ${df['charges'].sum():,.2f}")
    print(f"Min Charges: ${df['charges'].min():,.2f}")
    print(f"Max Charges: ${df['charges'].max():,.2f}")
    
    print("\n--- Outcome Distribution ---")
    print(df['outcome'].value_counts())
    
    print("\n--- Readmission Rate ---")
    readmission_rate = (df['readmission_30_days'] == 'Yes').sum() / len(df) * 100
    print(f"30-Day Readmission Rate: {readmission_rate:.2f}%")
    
    print("\n--- Insurance Type Distribution ---")
    print(df['insurance_type'].value_counts())

def diagnosis_analysis(df):
    """
    Analyze diagnosis patterns in the dataset.
    
    Parameters:
    df (pd.DataFrame): Patient dataset
    """
    print("\n" + "="*60)
    print("DIAGNOSIS ANALYSIS")
    print("="*60)
    
    print("\n--- Top 10 Diagnoses ---")
    top_diagnoses = df['diagnosis'].value_counts().head(10)
    print(top_diagnoses)
    
    print("\n--- Primary Conditions ---")
    primary_conditions = df['primary_condition'].value_counts()
    print(primary_conditions)
    
    print("\n--- Comorbidity Analysis ---")
    comorbidities = df['comorbidities'].value_counts()
    print(comorbidities)

def treatment_analysis(df):
    """
    Analyze treatment patterns and outcomes.
    
    Parameters:
    df (pd.DataFrame): Patient dataset
    """
    print("\n" + "="*60)
    print("TREATMENT ANALYSIS")
    print("="*60)
    
    print("\n--- Treatment Types ---")
    treatment_types = df['treatment_type'].value_counts()
    print(treatment_types)
    
    print("\n--- Treatment Outcomes by Type ---")
    outcome_by_treatment = pd.crosstab(df['treatment_type'], df['outcome'])
    print(outcome_by_treatment)
    
    print("\n--- Average Length of Stay by Treatment ---")
    los_by_treatment = df.groupby('treatment_type')['length_of_stay'].mean().sort_values(ascending=False)
    print(los_by_treatment)
    
    print("\n--- Average Charges by Treatment ---")
    charges_by_treatment = df.groupby('treatment_type')['charges'].mean().sort_values(ascending=False)
    for treatment, charge in charges_by_treatment.items():
        print(f"{treatment}: ${charge:,.2f}")

def demographic_analysis(df):
    """
    Analyze patient demographics and their impact on outcomes.
    
    Parameters:
    df (pd.DataFrame): Patient dataset
    """
    print("\n" + "="*60)
    print("DEMOGRAPHIC ANALYSIS")
    print("="*60)
    
    print("\n--- Age Groups ---")
    df['age_group'] = pd.cut(df['age'], bins=[0, 30, 40, 50, 60, 100], 
                             labels=['<30', '30-40', '40-50', '50-60', '60+'])
    age_groups = df['age_group'].value_counts().sort_index()
    print(age_groups)
    
    print("\n--- Outcomes by Age Group ---")
    outcome_by_age = pd.crosstab(df['age_group'], df['outcome'])
    print(outcome_by_age)
    
    print("\n--- Outcomes by Gender ---")
    outcome_by_gender = pd.crosstab(df['gender'], df['outcome'])
    print(outcome_by_gender)
    
    print("\n--- Average Charges by Age Group ---")
    charges_by_age = df.groupby('age_group')['charges'].mean()
    print(charges_by_age)

def financial_analysis(df):
    """
    Analyze financial aspects of patient care.
    
    Parameters:
    df (pd.DataFrame): Patient dataset
    """
    print("\n" + "="*60)
    print("FINANCIAL ANALYSIS")
    print("="*60)
    
    print("\n--- Charges by Insurance Type ---")
    charges_by_insurance = df.groupby('insurance_type')['charges'].agg(['mean', 'sum', 'count'])
    print(charges_by_insurance)
    
    print("\n--- Charges by Diagnosis ---")
    charges_by_diagnosis = df.groupby('diagnosis')['charges'].mean().sort_values(ascending=False).head(10)
    print(charges_by_diagnosis)
    
    print("\n--- Cost per Day Analysis ---")
    df['cost_per_day'] = df['charges'] / df['length_of_stay']
    print(f"Mean Cost per Day: ${df['cost_per_day'].mean():.2f}")
    print(f"Median Cost per Day: ${df['cost_per_day'].median():.2f}")

def generate_visualizations(df):
    """
    Generate visualizations for the dataset.
    
    Parameters:
    df (pd.DataFrame): Patient dataset
    """
    print("\n" + "="*60)
    print("GENERATING VISUALIZATIONS")
    print("="*60)
    
    # Create output directory for visualizations
    import os
    os.makedirs('visualizations', exist_ok=True)
    
    # 1. Age Distribution
    plt.figure(figsize=(10, 6))
    plt.hist(df['age'], bins=15, edgecolor='black', color='skyblue')
    plt.title('Age Distribution of Patients', fontsize=16, fontweight='bold')
    plt.xlabel('Age (years)', fontsize=12)
    plt.ylabel('Number of Patients', fontsize=12)
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('visualizations/age_distribution.png', dpi=300, bbox_inches='tight')
    print("✓ Saved: visualizations/age_distribution.png")
    plt.close()
    
    # 2. Gender Distribution
    plt.figure(figsize=(8, 6))
    gender_counts = df['gender'].value_counts()
    plt.pie(gender_counts, labels=gender_counts.index, autopct='%1.1f%%', 
            startangle=90, colors=['lightblue', 'lightcoral'])
    plt.title('Gender Distribution', fontsize=16, fontweight='bold')
    plt.tight_layout()
    plt.savefig('visualizations/gender_distribution.png', dpi=300, bbox_inches='tight')
    print("✓ Saved: visualizations/gender_distribution.png")
    plt.close()
    
    # 3. Top Diagnoses
    plt.figure(figsize=(12, 6))
    top_diagnoses = df['diagnosis'].value_counts().head(10)
    plt.barh(range(len(top_diagnoses)), top_diagnoses.values, color='steelblue')
    plt.yticks(range(len(top_diagnoses)), top_diagnoses.index)
    plt.xlabel('Number of Patients', fontsize=12)
    plt.title('Top 10 Diagnoses', fontsize=16, fontweight='bold')
    plt.gca().invert_yaxis()
    plt.tight_layout()
    plt.savefig('visualizations/top_diagnoses.png', dpi=300, bbox_inches='tight')
    print("✓ Saved: visualizations/top_diagnoses.png")
    plt.close()
    
    # 4. Length of Stay Distribution
    plt.figure(figsize=(10, 6))
    plt.hist(df['length_of_stay'], bins=15, edgecolor='black', color='lightgreen')
    plt.title('Length of Stay Distribution', fontsize=16, fontweight='bold')
    plt.xlabel('Length of Stay (days)', fontsize=12)
    plt.ylabel('Number of Patients', fontsize=12)
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('visualizations/length_of_stay.png', dpi=300, bbox_inches='tight')
    print("✓ Saved: visualizations/length_of_stay.png")
    plt.close()
    
    # 5. Charges Distribution
    plt.figure(figsize=(10, 6))
    plt.hist(df['charges'], bins=20, edgecolor='black', color='salmon')
    plt.title('Charges Distribution', fontsize=16, fontweight='bold')
    plt.xlabel('Charges ($)', fontsize=12)
    plt.ylabel('Number of Patients', fontsize=12)
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('visualizations/charges_distribution.png', dpi=300, bbox_inches='tight')
    print("✓ Saved: visualizations/charges_distribution.png")
    plt.close()
    
    # 6. Outcome Distribution
    plt.figure(figsize=(8, 6))
    outcome_counts = df['outcome'].value_counts()
    plt.bar(outcome_counts.index, outcome_counts.values, color=['green', 'orange', 'blue'])
    plt.title('Patient Outcomes Distribution', fontsize=16, fontweight='bold')
    plt.xlabel('Outcome', fontsize=12)
    plt.ylabel('Number of Patients', fontsize=12)
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.savefig('visualizations/outcome_distribution.png', dpi=300, bbox_inches='tight')
    print("✓ Saved: visualizations/outcome_distribution.png")
    plt.close()
    
    # 7. Treatment Type vs Charges
    plt.figure(figsize=(12, 6))
    treatment_charges = df.groupby('treatment_type')['charges'].mean().sort_values(ascending=False)
    plt.bar(treatment_charges.index, treatment_charges.values, color='teal')
    plt.title('Average Charges by Treatment Type', fontsize=16, fontweight='bold')
    plt.xlabel('Treatment Type', fontsize=12)
    plt.ylabel('Average Charges ($)', fontsize=12)
    plt.xticks(rotation=45, ha='right')
    plt.tight_layout()
    plt.savefig('visualizations/treatment_charges.png', dpi=300, bbox_inches='tight')
    print("✓ Saved: visualizations/treatment_charges.png")
    plt.close()
    
    # 8. Age vs Charges Scatter
    plt.figure(figsize=(10, 6))
    plt.scatter(df['age'], df['charges'], alpha=0.6, color='purple')
    plt.title('Age vs Charges', fontsize=16, fontweight='bold')
    plt.xlabel('Age (years)', fontsize=12)
    plt.ylabel('Charges ($)', fontsize=12)
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('visualizations/age_vs_charges.png', dpi=300, bbox_inches='tight')
    print("✓ Saved: visualizations/age_vs_charges.png")
    plt.close()

def export_summary_report(df, output_file='analysis_report.txt'):
    """
    Export a comprehensive summary report to a text file.
    
    Parameters:
    df (pd.DataFrame): Patient dataset
    output_file (str): Output file path
    """
    import sys
    from io import StringIO
    
    # Redirect stdout to capture print statements
    old_stdout = sys.stdout
    sys.stdout = report = StringIO()
    
    # Run all analyses
    basic_statistics(df)
    diagnosis_analysis(df)
    treatment_analysis(df)
    demographic_analysis(df)
    financial_analysis(df)
    
    # Get the report content
    report_content = report.getvalue()
    sys.stdout = old_stdout
    
    # Write to file
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write("="*60 + "\n")
        f.write("HEALTHCARE PATIENT DATASET - ANALYSIS REPORT\n")
        f.write("="*60 + "\n")
        f.write(f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        f.write(f"Author: RSK World (https://rskworld.in)\n")
        f.write("="*60 + "\n\n")
        f.write(report_content)
    
    print(f"✓ Analysis report saved to: {output_file}")

def main():
    """
    Main function to run all analyses.
    """
    print("\n" + "="*60)
    print("HEALTHCARE PATIENT DATASET ANALYSIS")
    print("="*60)
    print("Author: RSK World")
    print("Website: https://rskworld.in")
    print("Email: help@rskworld.in")
    print("Phone: +91 93305 39277")
    print("="*60)
    
    # Load data
    df = load_data()
    if df is None:
        return
    
    # Display dataset info
    print("\n--- Dataset Info ---")
    print(df.info())
    
    print("\n--- First Few Rows ---")
    print(df.head())
    
    # Run analyses
    basic_statistics(df)
    diagnosis_analysis(df)
    treatment_analysis(df)
    demographic_analysis(df)
    financial_analysis(df)
    
    # Generate visualizations
    generate_visualizations(df)
    
    # Export report
    export_summary_report(df)
    
    print("\n" + "="*60)
    print("ANALYSIS COMPLETE!")
    print("="*60)
    print("\nGenerated Files:")
    print("  - visualizations/ (directory with charts)")
    print("  - analysis_report.txt (comprehensive report)")
    print("\n")

if __name__ == "__main__":
    main()

403 lines•13.8 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer