# This module contains functions to collapse multiple rows of the same disease into a single row with aggregated symptoms. import pandas as pd from .vocabulary import normalize_symptom # This function takes a DataFrame with multiple rows per disease and collapses them into a single row per disease def collapse_disease_rows(df: pd.DataFrame) -> pd.DataFrame: """ Collapse multiple rows per condition into a single row with the union of all normalized symptoms. Also preserve the number of original rows per disease (for rarity scoring). """ symptom_cols = [c for c in df.columns if c.lower().startswith("symptom")] # Count how many times each disease appears in the original dataset counts = ( df["Disease"] .str.strip() .str.lower() .value_counts() .to_dict() ) collapsed = {} # Iterate through each row and aggregate symptoms for each disease for _, row in df.iterrows(): disease = row["Disease"].strip().lower() if disease not in collapsed: collapsed[disease] = set() for s in row[symptom_cols]: if isinstance(s, str) and s.strip(): collapsed[disease].add(normalize_symptom(s)) records = [] # Create a new DataFrame with one row per disease, including the count of original rows for rarity scoring for disease, symptoms in collapsed.items(): records.append( { "Disease": disease, "Symptoms": sorted(symptoms), "Count": counts.get(disease, 1), # ⭐ critical for rarity penalty } ) return pd.DataFrame(records)