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.pyGITHUB_PUSH_SUMMARY.mdadvanced_analysis_report.txt
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
GITHUB_PUSH_SUMMARY.md
Raw Download

GITHUB_PUSH_SUMMARY.md

# GitHub Push Summary

<!--
Author: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277
-->

## ✅ Successfully Pushed to GitHub

**Repository**: https://github.com/rskworld/healthcare-patients.git
**Tag**: v1.0.0
**Branch**: main

---

## 📦 What Was Pushed

### All Project Files (28 files total)

#### Core Data Files
- ✅ `healthcare_patients.csv` - Main dataset (30 patients, 26 features)
- ✅ `healthcare_patients.xlsx` - Excel export with 6 sheets
- ✅ `healthcare_patients.json` - JSON export with metadata

#### Python Scripts
- ✅ `analyze_patients.py` - Basic analysis script
- ✅ `advanced_analysis.py` - ML & advanced analytics
- ✅ `export_to_excel.py` - Excel export utility
- ✅ `export_to_json.py` - JSON export utility
- ✅ `validate_data.py` - Data validation script

#### Web Interface
- ✅ `index.html` - Interactive dashboard with Chart.js

#### Documentation
- ✅ `README.md` - Complete project documentation
- ✅ `QUICKSTART.md` - Quick start guide
- ✅ `ADVANCED_FEATURES.md` - Advanced features documentation
- ✅ `PROJECT_SUMMARY.md` - Project overview
- ✅ `FILES_SUMMARY.md` - File descriptions
- ✅ `PROJECT_INFO.md` - Project metadata
- ✅ `IMAGE_DESCRIPTION.md` - Image requirements
- ✅ `RELEASE_NOTES.md` - **NEW** Release notes for v1.0.0

#### Configuration
- ✅ `requirements.txt` - Python dependencies
- ✅ `.gitignore` - Git ignore rules
- ✅ `LICENSE` - MIT License

#### Generated Files
- ✅ `advanced_analysis_report.txt` - ML analysis report
- ✅ `visualizations/` - Directory with 8 visualization PNG files

---

## 🏷️ Git Tag Created

**Tag**: `v1.0.0`
**Message**:
```
Version 1.0.0 - Initial Release

Healthcare Patient Dataset with Advanced Features

Features:
- 30 patient records with 26 features
- Basic and advanced analysis tools
- Machine learning models
- Interactive web dashboard
- Multiple export formats (CSV, Excel, JSON)
- Comprehensive documentation
- 15+ visualizations

Author: RSK World (https://rskworld.in)
```

---

## 📝 Commits Made

1. **Initial commit** (6b48347)
- Healthcare Patient Dataset with Advanced Features
- All 28 files committed

2. **Add release notes** (e15680f)
- Added RELEASE_NOTES.md for v1.0.0

---

## 🚀 Next Steps

### To Create a Release on GitHub:

1. Go to: https://github.com/rskworld/healthcare-patients/releases
2. Click "Draft a new release"
3. Select tag: `v1.0.0`
4. Title: `v1.0.0 - Initial Release`
5. Description: Copy content from `RELEASE_NOTES.md`
6. Click "Publish release"

### Repository Links:

- **Main Repository**: https://github.com/rskworld/healthcare-patients
- **Releases**: https://github.com/rskworld/healthcare-patients/releases
- **Tags**: https://github.com/rskworld/healthcare-patients/tags

---

## 📊 Repository Statistics

- **Total Files**: 28
- **Total Lines**: 3,929+ insertions
- **Visualizations**: 8 PNG files
- **Python Scripts**: 5
- **Documentation Files**: 8
- **Data Files**: 3 (CSV, Excel, JSON)

---

## ✅ Verification

All files have been:
- ✅ Committed to git
- ✅ Pushed to GitHub
- ✅ Tagged as v1.0.0
- ✅ Tag pushed to remote
- ✅ Release notes created

---

## 📞 Contact

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

---

**Status**: ✅ Successfully pushed to GitHub with tag v1.0.0

advanced_analysis_report.txt
Raw Download
Find: Go to:
============================================================
ADVANCED ANALYSIS REPORT - HEALTHCARE PATIENT DATASET
============================================================
Generated on: 2025-12-28 15:15:52
Author: RSK World (https://rskworld.in)
============================================================


============================================================
CORRELATION ANALYSIS
============================================================

Correlation Matrix:
                     age  length_of_stay   charges
age             1.000000        0.658319  0.526026
length_of_stay  0.658319        1.000000  0.566531
charges         0.526026        0.566531  1.000000

[OK] Saved: visualizations/correlation_matrix.png

Strong Correlations (|r| > 0.3):
  age <-> length_of_stay: 0.658
  age <-> charges: 0.526
  length_of_stay <-> charges: 0.567

============================================================
STATISTICAL TESTS
============================================================

T-test: Charges by Gender
  T-statistic: 0.8402
  P-value: 0.4079
  Significant: No (p < 0.05)

T-test: Length of Stay by Outcome (Recovered vs Improved)
  T-statistic: -6.4528
  P-value: 0.0000
  Significant: Yes (p < 0.05)

Chi-square Test: Outcome vs Treatment Type
  Chi-square: 36.8210
  P-value: 0.0247
  Degrees of freedom: 22
  Significant: Yes (p < 0.05)

============================================================
READMISSION PREDICTION MODEL
============================================================

Model Performance:
  Accuracy: 1.0000 (100.00%)

Classification Report:
              precision    recall  f1-score   support

          No       1.00      1.00      1.00         9

    accuracy                           1.00         9
   macro avg       1.00      1.00      1.00         9
weighted avg       1.00      1.00      1.00         9


Feature Importance:
  length_of_stay: 0.4294
  charges: 0.3436
  age: 0.2270

[OK] Saved: visualizations/feature_importance.png

============================================================
CHARGES PREDICTION MODEL
============================================================

Model Performance:
  R² Score: -1.2788
  RMSE: $7,539.40

[OK] Saved: visualizations/charges_prediction.png
79 lines•2.3 KB
text
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

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