diff --git a/pandas/core/col.py b/pandas/core/col.py index 39c4a7fd016c2..814b714bdbe2f 100644 --- a/pandas/core/col.py +++ b/pandas/core/col.py @@ -37,6 +37,8 @@ "__lt__": "<", "__eq__": "==", "__ne__": "!=", + "__and__": "&", + "__rand__": "&", } @@ -157,6 +159,12 @@ def __mod__(self, other: Any) -> Expression: def __rmod__(self, other: Any) -> Expression: return self._with_binary_op("__rmod__", other) + def __and__(self, other: Any) -> Expression: + return self._with_binary_op("__and__", other) + + def __rand__(self, other: Any) -> Expression: + return self._with_binary_op("__rand__", other) + def __array_ufunc__( self, ufunc: Callable[..., Any], method: str, *inputs: Any, **kwargs: Any ) -> Expression: diff --git a/pandas/tests/test_col.py b/pandas/tests/test_col.py index c884540abfed0..6883532432465 100644 --- a/pandas/tests/test_col.py +++ b/pandas/tests/test_col.py @@ -46,6 +46,36 @@ def test_col_simple( assert str(expr) == expected_str +@pytest.mark.parametrize( + ("expr", "expected_values", "expected_str"), + [ + ( + (pd.col("a") >= 3) & (pd.col("a") <= 5), + [3, 4, 5], + "((col('a') >= 3) & (col('a') <= 5))", + ), + ( + (pd.col("b") >= 20) & (pd.col("a") <= 5), + [1, 2, 3], + "((col('b') >= 20) & (col('a') <= 5))", + ), + ( + (pd.col("b") >= 20) & (pd.col("a") <= 5) & (pd.col("b") < 22), + [2, 3], + "(((col('b') >= 20) & (col('a') <= 5)) & (col('b') < 22))", + ), + ], +) +def test_col_bool( + expr: Expression, expected_values: list[object], expected_str: str +) -> None: + df = pd.DataFrame({"a": list(range(1, 21)), "b": list(range(22, 2, -1))}) + result = df.loc[expr] + ls = result["a"].tolist() + assert ls == expected_values + assert str(expr) == expected_str + + @pytest.mark.parametrize( ("expr", "expected_values", "expected_str"), [