Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1423,6 +1423,7 @@ Other
array if the array shares data with the original DataFrame or Series (:ref:`copy_on_write_read_only_na`).
This logic is expanded to accessing the underlying pandas ExtensionArray
through ``.array`` (or ``.values`` depending on the dtype) as well (:issue:`61925`).
- Fixed bug that pd.col does not support & for combining conditions in .loc (:issue:`63322`)

.. ***DO NOT USE THIS SECTION***

Expand Down
8 changes: 8 additions & 0 deletions pandas/core/col.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
"__lt__": "<",
"__eq__": "==",
"__ne__": "!=",
"__and__": "&",
"__rand__": "&",
}


Expand Down Expand Up @@ -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:
Expand Down
30 changes: 30 additions & 0 deletions pandas/tests/test_col.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
[
Expand Down
Loading