Skip to content

panel_aware_rename

yohou.utils.panel.panel_aware_rename(col, fn)

Apply a rename function to a column name while preserving the panel group prefix.

For panel data columns following the <GROUP>__<SERIES> convention, the rename function is applied only to the series (member) portion, leaving the group prefix intact: <GROUP>__fn(<SERIES>).

For global columns (no __ separator), the rename function is applied to the entire column name: fn(<COLUMN>).

Parameters

Name Type Description Default
col str

Column name to rename.

required
fn callable

Function that takes a string and returns a string. Applied to the series part of panel columns or the full name for global columns.

required

Returns

Type Description
str

Renamed column name with panel group prefix preserved.

Examples

>>> panel_aware_rename("sales", lambda s: f"log_{s}")
'log_sales'
>>> panel_aware_rename("store_1__sales", lambda s: f"log_{s}")
'store_1__log_sales'
>>> panel_aware_rename("store_1__sales", lambda s: f"{s}_lag_1")
'store_1__sales_lag_1'

See Also

Source Code

Show/Hide source
def panel_aware_rename(col: str, fn: Callable[[str], str]) -> str:
    """Apply a rename function to a column name while preserving the panel group prefix.

    For panel data columns following the ``<GROUP>__<SERIES>`` convention,
    the rename function is applied only to the series (member) portion,
    leaving the group prefix intact: ``<GROUP>__fn(<SERIES>)``.

    For global columns (no ``__`` separator), the rename function is applied
    to the entire column name: ``fn(<COLUMN>)``.

    Parameters
    ----------
    col : str
        Column name to rename.
    fn : callable
        Function that takes a string and returns a string.
        Applied to the series part of panel columns or the full name
        for global columns.

    Returns
    -------
    str
        Renamed column name with panel group prefix preserved.

    Examples
    --------
    >>> panel_aware_rename("sales", lambda s: f"log_{s}")
    'log_sales'
    >>> panel_aware_rename("store_1__sales", lambda s: f"log_{s}")
    'store_1__log_sales'
    >>> panel_aware_rename("store_1__sales", lambda s: f"{s}_lag_1")
    'store_1__sales_lag_1'

    See Also
    --------
    - [`panel_aware_prefix`][yohou.utils.panel.panel_aware_prefix] : Convenience wrapper for adding a prefix.
    - [`panel_aware_suffix`][yohou.utils.panel.panel_aware_suffix] : Convenience wrapper for adding a suffix.

    """
    if "__" in col:
        group, member = col.split("__", 1)
        return f"{group}__{fn(member)}"
    return fn(col)