# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/Tutorials/04_manipulate.ipynb.

# %% auto 0
__all__ = ['set_row_as_header', 'create_dec_dummies', 'create_region_district_mapping', 'standardize_district_names',
           'populate_region_column']

# %% ../nbs/Tutorials/04_manipulate.ipynb 2
import pandas as pd

def set_row_as_header(df:pd.DataFrame=None, row_num:int=None) -> pd.DataFrame:
    """
    Set the specified row as column names for the given DataFrame
    """

    if row_num is None or df is None:
        raise ValueError("df and row_num must be an provided")
    
    new_header = df.iloc[row_num]  
    df = df[row_num + 1:]  
    df.columns = new_header  

    # set header as strings
    df.columns = df.columns.astype(str)    
    
    return df

# %% ../nbs/Tutorials/04_manipulate.ipynb 3
def create_dec_dummies(df):
    # Find columns that end with '_dec'
    dec_columns = [col for col in df.columns if col.endswith('_dec')]
    
    # Explode each list in the columns, and concatenate all exploded columns together
    df_expanded = pd.concat([df[col].explode() for col in dec_columns], axis=1)
    
    # Create dummies for each unique value in the columns ending with '_dec'
    dummies = pd.get_dummies(df_expanded, prefix=dec_columns).groupby(level=0).sum()
    
    # Concatenate the original DataFrame with the dummies
    df = pd.concat([df, dummies], axis=1).drop(columns=dec_columns)
    
    return df

# %% ../nbs/Tutorials/04_manipulate.ipynb 6
import pandas as pd

def create_region_district_mapping():
    """
    Creates a dictionary mapping districts to their respective regions
    Including explicit entries for GAC and Standard variants
    All district keys are in lowercase for consistent matching
    """
    mapping = {
        # South West Region
        'mitooma': 'South_West',
        'rubanda': 'South_West',
        'kanungu': 'South_West',
        'rukungiri': 'South_West',
        'rubirizi': 'South_West',
        'rukiga': 'South_West',
        
        # Mid West Region
        'kagadi': 'Mid_West',
        'kagadi - gac': 'Mid_West',
        'kagadi - standard': 'Mid_West',
        'kagadi_gac': 'Mid_West',
        'kagadi_standard': 'Mid_West',
        'kyenjojo': 'Mid_West',
        'kyenjojo - gac': 'Mid_West',
        'kyenjojo - standard': 'Mid_West',
        'kibaale': 'Mid_West',
        'kiryandongo': 'Mid_West',
        
        # Eastern Region
        'kaliro': 'Eastern',
        'luuka': 'Eastern'
    }
    return mapping

# %% ../nbs/Tutorials/04_manipulate.ipynb 7
def standardize_district_names(df, district_col='pre_district'):
    """
    Standardizes district names by converting to lowercase and stripping whitespace
    
    Parameters:
    df (pandas.DataFrame): Input dataframe
    district_col (str): Name of the district column
    
    Returns:
    pandas.DataFrame: DataFrame with standardized district names
    """
    df = df.copy()
    df[district_col] = df[district_col].str.strip().str.lower()
    return df

# %% ../nbs/Tutorials/04_manipulate.ipynb 8
def populate_region_column(df, district_col='pre_district', region_col='region'):
    """
    Populates the region column in a dataframe based on the district-region mapping
    Handles case sensitivity by converting districts to lowercase before mapping
    
    Parameters:
    df (pandas.DataFrame): Input dataframe
    district_col (str): Name of the district column
    region_col (str): Name of the region column to be populated
    
    Returns:
    pandas.DataFrame: DataFrame with populated region column
    """
    # First standardize the district names
    df = standardize_district_names(df, district_col)
    
    # Create and apply the mapping
    mapping = create_region_district_mapping()
    df[region_col] = df[district_col].map(mapping)
    
    # Print any districts that weren't matched
    unmatched = df[df[region_col].isna()][district_col].unique()
    if len(unmatched) > 0:
        print(f"Warning: The following districts were not found in the mapping: {unmatched}")
    
    return df
