Skip to content

monkey_patch

patch_dataframe_libraries()

Applies two patches to the DataFrame and Series classes of both pandas and polars. 1) Patches arithmetic operators (e.g. __add__) such that operations between DataFrames/Series and Expressionables are not supported (i.e. return NotImplemented). This leads Python to try the reverse operation (e.g. __radd__) which is supported by the Expressionable class. 2) Adds a to_expr method to DataFrame/Series that allows them to be converted to an Expression object. Series become dataframes and dataframes become expressions where everything but the last column are treated as dimensions.

Source code in pyoframe/monkey_patch.py
def patch_dataframe_libraries():
    """
    Applies two patches to the DataFrame and Series classes of both pandas and polars.
    1) Patches arithmetic operators (e.g. `__add__`) such that operations between DataFrames/Series and `Expressionable`s
        are not supported (i.e. `return NotImplemented`). This leads Python to try the reverse operation (e.g. `__radd__`)
        which is supported by the `Expressionable` class.
    2) Adds a `to_expr` method to DataFrame/Series that allows them to be converted to an `Expression` object.
        Series become dataframes and dataframes become expressions where everything but the last column are treated as dimensions.
    """
    _patch_class(pd.DataFrame)
    _patch_class(pd.Series)
    _patch_class(pl.DataFrame)
    _patch_class(pl.Series)
    pl.DataFrame.to_expr = _dataframe_to_expr
    pl.Series.to_expr = lambda self: self.to_frame().to_expr()
    pd.DataFrame.to_expr = lambda self: pl.from_pandas(self).to_expr()
    pd.Series.to_expr = lambda self: self.to_frame().reset_index().to_expr()