bucketplot.py
def group_and_agg(df_w_buckets, x_var, stat_wgt=None, stat_vars=None):
    """
    Group by bucket and calculate aggregate values in each bucket
    
    df_w_buckets: Result of an 'assign_buckets' function.
        i.e. a DataFrame with a `bucket` column the is Categorical
        with Interval categories that partition a range.
        Rows with missing `bucket` value are excluded from the grouping.
    x_var: Column name of variable that will be plotted on the x axis.
    stat_wgt: Weights for the weighted distributions of stat_vars.
        If None (default) or 'const' then equal weights are used for all rows.
        Must be non-negative with at least one postive value.
    stat_vars: 
        If None (default) or empty list, no values are calculated.
    
    Returns: Aggregated DataFrame for plotting.
    """
    # Set defaults
    if stat_wgt is None:
        stat_wgt = 'const'
    if stat_wgt == 'const':
        df_w_buckets = df_w_buckets.assign(const = 1)
    if stat_vars is None:
        stat_vars = []
    
    # Format inputs and defaults
    if not isinstance(stat_vars, list):
        stat_vars = [stat_vars]
    
    # Variables for which we want the (weighted) distribution in each bucket
    agg_vars_all = stat_vars
    if np.issubdtype(df_w_buckets[x_var].dtype, np.number):
        agg_vars_all = [x_var] + agg_vars_all
    # Ensure they are unique (and maintain order)
    agg_vars = pd.Series(agg_vars_all).drop_duplicates()
    
    df_agg = df_w_buckets.assign(
        **{col + '_x_wgt': (
            lambda df, col=col: df[col] * df[stat_wgt]
        ) for col in agg_vars},
    ).groupby(
        # Group by the buckets
        'bucket', sort=False
    ).agg(
        # Aggregate calculation for rows in each bucket
        n_obs=('bucket', 'size'),  # It is possible that a bucket contains zero rows
        **{col: (col, 'sum') for col in [stat_wgt]},
        **{stat_var + '_wgt_sum': (
            stat_var + '_x_wgt', 'sum'
        ) for stat_var in agg_vars},
        x_min=(x_var, 'min'),
        x_max=(x_var, 'max'),
    ).pipe(
        # Convert the index to an IntervalIndex
        lambda df: df.set_index(df.index.categories)
    ).sort_index().assign(
        # Calculate the weighted average of the stats
        **{stat_var + '_wgt_av': (
            lambda df, stat_var=stat_var: df[stat_var + '_wgt_sum'] / df[stat_wgt]
        ) for stat_var in agg_vars},
    )
    
    return(df_agg)

    Group by bucket and calculate aggregate values in each bucket
    
    df_w_buckets: Result of an 'assign_buckets' function.
        i.e. a DataFrame with a `bucket` column the is Categorical
        with Interval categories that partition a range.
        Rows with missing `bucket` value are excluded from the grouping.
    x_var: Column name of variable that will be plotted on the x axis.
    stat_wgt: Weights for the weighted distributions of stat_vars.
        If None (default) or 'const' then equal weights are used for all rows.
        Must be non-negative with at least one postive value.
    stat_vars: 
        If None (default) or empty list, no values are calculated.
    
    Returns: Aggregated DataFrame for plotting.
    
Group by bucket and calculate aggregate values in each bucket
df_w_buckets: Result of an 'assign_buckets' function.

Aggregated DataFrame for plotting.
Group by bucket and calculate aggregate values in each bucket df_w_buckets : Result of an ' assign_buckets ' function . Aggregated DataFrame for plotting .
def group_and_agg(df_w_buckets, x_var, stat_wgt=None, stat_vars=None):
    if stat_wgt is None:
        stat_wgt = 'const'
    if stat_wgt == 'const':
        df_w_buckets = df_w_buckets.assign(const = 1)
    if stat_vars is None:
        stat_vars = []
    if not isinstance(stat_vars, list):
        stat_vars = [stat_vars]
    agg_vars_all = stat_vars
    if np.issubdtype(df_w_buckets[x_var].dtype, np.number):
        agg_vars_all = [x_var] + agg_vars_all
    agg_vars = pd.Series(agg_vars_all).drop_duplicates()
    df_agg = df_w_buckets.assign(
        **{col + '_x_wgt': (
            lambda df, col=col: df[col] * df[stat_wgt]
        ) for col in agg_vars},
    ).groupby(
        'bucket', sort=False
    ).agg(
        n_obs=('bucket', 'size'),  
        **{col: (col, 'sum') for col in [stat_wgt]},
        **{stat_var + '_wgt_sum': (
            stat_var + '_x_wgt', 'sum'
        ) for stat_var in agg_vars},
        x_min=(x_var, 'min'),
        x_max=(x_var, 'max'),
    ).pipe(
        lambda df: df.set_index(df.index.categories)
    ).sort_index().assign(
        **{stat_var + '_wgt_av': (
            lambda df, stat_var=stat_var: df[stat_var + '_wgt_sum'] / df[stat_wgt]
        ) for stat_var in agg_vars},
    )
    return(df_agg)
def group_and_agg ( df_w_buckets , x_var , stat_wgt = None , stat_vars = None ) : if stat_wgt is None : stat_wgt = 'const' if stat_wgt == 'const' : df_w_buckets = df_w_buckets . assign ( const = 1 ) if stat_vars is None : stat_vars = [ ] if not isinstance ( stat_vars , list ) : stat_vars = [ stat_vars ] agg_vars_all = stat_vars if np . issubdtype ( df_w_buckets [ x_var ] . dtype , np . number ) : agg_vars_all = [ x_var ] + agg_vars_all agg_vars = pd . Series ( agg_vars_all ) . drop_duplicates ( ) df_agg = df_w_buckets . assign ( ** { col + '_x_wgt' : ( lambda df , col = col : df [ col ] * df [ stat_wgt ] ) for col in agg_vars } , ) . groupby ( 'bucket' , sort = False ) . agg ( n_obs = ( 'bucket' , 'size' ) , ** { col : ( col , 'sum' ) for col in [ stat_wgt ] } , ** { stat_var + '_wgt_sum' : ( stat_var + '_x_wgt' , 'sum' ) for stat_var in agg_vars } , x_min = ( x_var , 'min' ) , x_max = ( x_var , 'max' ) , ) . pipe ( lambda df : df . set_index ( df . index . categories ) ) . sort_index ( ) . assign ( ** { stat_var + '_wgt_av' : ( lambda df , stat_var = stat_var : df [ stat_var + '_wgt_sum' ] / df [ stat_wgt ] ) for stat_var in agg_vars } , ) return ( df_agg )
Group by bucket and calculate aggregate values in each bucket
df_w_buckets: Result of an 'assign_buckets' function.
Group by bucket and calculate aggregate values in each bucket df_w_buckets : Result of an ' assign_buckets ' function .
"""
    Group by bucket and calculate aggregate values in each bucket
    
    df_w_buckets: Result of an 'assign_buckets' function.
        i.e. a DataFrame with a `bucket` column the is Categorical
        with Interval categories that partition a range.
        Rows with missing `bucket` value are excluded from the grouping.
    x_var: Column name of variable that will be plotted on the x axis.
    stat_wgt: Weights for the weighted distributions of stat_vars.
        If None (default) or 'const' then equal weights are used for all rows.
        Must be non-negative with at least one postive value.
    stat_vars: 
        If None (default) or empty list, no values are calculated.
    
    Returns: Aggregated DataFrame for plotting.
    """ # Set defaults # Format inputs and defaults # Variables for which we want the (weighted) distribution in each bucket # Ensure they are unique (and maintain order) # Group by the buckets # Aggregate calculation for rows in each bucket # It is possible that a bucket contains zero rows # Convert the index to an IntervalIndex # Calculate the weighted average of the stats
df_w_buckets
x_var
stat_wgt
stat_vars