Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
3d17e56
ENH: Introduce `pandas.col`
MarcoGorelli Aug 13, 2025
9fcaba3
api test, typing
MarcoGorelli Aug 13, 2025
b41b99d
typing
MarcoGorelli Aug 14, 2025
60c09c2
add pretty repr
MarcoGorelli Aug 14, 2025
9e4e0c5
improve error message
MarcoGorelli Aug 16, 2025
fe78aa2
test repr
MarcoGorelli Aug 16, 2025
04044af
test namespaces
MarcoGorelli Aug 16, 2025
a95aeb4
docs
MarcoGorelli Aug 16, 2025
4dc8e55
reference in dsintro
MarcoGorelli Aug 16, 2025
13d8e5c
Merge remote-tracking branch 'upstream/main' into pandas-col
MarcoGorelli Aug 16, 2025
e2aeb4f
fixup link
MarcoGorelli Aug 16, 2025
fa3e793
fixup docs
MarcoGorelli Aug 16, 2025
0bc918a
fixup
MarcoGorelli Aug 16, 2025
a0939f9
add test file
MarcoGorelli Aug 16, 2025
a703982
simplify, support custom series extensions too
MarcoGorelli Aug 17, 2025
48228cc
test accessor
MarcoGorelli Aug 17, 2025
d6f55a1
:pencil: fix typo
MarcoGorelli Aug 17, 2025
b2ed136
typing
MarcoGorelli Aug 17, 2025
c8f0193
move Expr to api.typing
MarcoGorelli Aug 17, 2025
e6ea343
move Expr to api/typing
MarcoGorelli Aug 17, 2025
96990d6
rename Expr to Expression
MarcoGorelli Aug 17, 2025
548ee20
fix return type
MarcoGorelli Aug 17, 2025
cfbd5a3
support NumPy ufuncs
MarcoGorelli Aug 19, 2025
e74438c
support NumPy ufuncs too
MarcoGorelli Aug 19, 2025
b4de244
Merge remote-tracking branch 'upstream/main' into pandas-col
MarcoGorelli Aug 19, 2025
31192e0
Merge branch 'pandas-col' of github.com:MarcoGorelli/pandas into pand…
MarcoGorelli Aug 19, 2025
83b70e8
simplify repr_str type
MarcoGorelli Aug 19, 2025
3b6906b
fix typing, avoid floating point inaccuracies
MarcoGorelli Aug 19, 2025
9fed80e
add to api reference
MarcoGorelli Aug 19, 2025
edb0e38
truncate output for wide dataframes
MarcoGorelli Aug 19, 2025
72faba9
make `max_cols` variable
MarcoGorelli Aug 19, 2025
b6f4961
truncate based on message length rather than number of columns
MarcoGorelli Aug 19, 2025
3791cf6
fixup docstring
MarcoGorelli Aug 19, 2025
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
72 changes: 34 additions & 38 deletions pandas/core/col.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,32 @@ def _parse_kwargs(df: DataFrame, **kwargs: Any) -> dict[Hashable, Series]:
}


def _pretty_print_args_kwargs(*args: Any, **kwargs: Any) -> str:
inputs_repr = ", ".join(
arg._repr_str if isinstance(arg, Expression) else repr(arg) for arg in args
)
kwargs_repr = ", ".join(
f"{k}={v._repr_str if isinstance(v, Expression) else v!r}"
for k, v in kwargs.items()
)

all_args = []
if inputs_repr:
all_args.append(inputs_repr)
if kwargs_repr:
all_args.append(kwargs_repr)

return ", ".join(all_args)


class Expression:
"""
Class representing a deferred column.

This is not meant to be instantiated directly. Instead, use :meth:`pandas.col`.
"""

def __init__(
self, func: Callable[[DataFrame], Any], repr_str: str | None = None
) -> None:
def __init__(self, func: Callable[[DataFrame], Any], repr_str: str) -> None:
self._func = func
self._repr_str = repr_str

Expand Down Expand Up @@ -138,6 +154,19 @@ def __mod__(self, other: Any) -> Expression:
def __rmod__(self, other: Any) -> Expression:
return self._with_binary_op("__rmod__", other)

def __array_ufunc__(
self, ufunc: Callable[..., Any], method: str, *inputs: Any, **kwargs: Any
) -> Expression:
def func(df: DataFrame) -> Any:
parsed_inputs = _parse_args(df, *inputs)
parsed_kwargs = _parse_kwargs(df, *kwargs)
return ufunc(*parsed_inputs, **parsed_kwargs)

args_str = _pretty_print_args_kwargs(*inputs, **kwargs)
repr_str = f"{ufunc.__name__}({args_str})"

return Expression(func, repr_str)

# Everything else
def __getattr__(self, attr: str, /) -> Any:
if attr in Series._accessors:
Expand All @@ -149,23 +178,7 @@ def func(df: DataFrame, *args: Any, **kwargs: Any) -> Any:
return getattr(self(df), attr)(*parsed_args, **parsed_kwargs)

def wrapper(*args: Any, **kwargs: Any) -> Expression:
# Create a readable representation for method calls
args_repr = ", ".join(
repr(arg._repr_str if isinstance(arg, Expression) else arg)
for arg in args
)
kwargs_repr = ", ".join(
f"{k}={v._repr_str if isinstance(v, Expression) else v!r}"
for k, v in kwargs.items()
)

all_args = []
if args_repr:
all_args.append(args_repr)
if kwargs_repr:
all_args.append(kwargs_repr)

args_str = ", ".join(all_args)
args_str = _pretty_print_args_kwargs(*args, **kwargs)
repr_str = f"{self._repr_str}.{attr}({args_str})"

return Expression(lambda df: func(df, *args, **kwargs), repr_str)
Expand Down Expand Up @@ -200,25 +213,8 @@ def func(df: DataFrame, *args: Any, **kwargs: Any) -> Any:
)

def wrapper(*args: Any, **kwargs: Any) -> Expression:
# Create a readable representation for namespace method calls
args_repr = ", ".join(
repr(arg._repr_str if isinstance(arg, Expression) else arg)
for arg in args
)
kwargs_repr = ", ".join(
f"{k}={v._repr_str if isinstance(v, Expression) else v!r}"
for k, v in kwargs.items()
)

all_args = []
if args_repr:
all_args.append(args_repr)
if kwargs_repr:
all_args.append(kwargs_repr)

args_str = ", ".join(all_args)
args_str = _pretty_print_args_kwargs(*args, **kwargs)
repr_str = f"{self._func._repr_str}.{self._namespace}.{attr}({args_str})"

return Expression(lambda df: func(df, *args, **kwargs), repr_str)

return wrapper
Expand Down
3 changes: 3 additions & 0 deletions pandas/tests/test_col.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import datetime

import numpy as np
import pytest

import pandas as pd
Expand Down Expand Up @@ -31,6 +32,8 @@
(pd.col("a") < 1, [False, False], "(col('a') < 1)"),
(pd.col("a") <= 1, [True, False], "(col('a') <= 1)"),
(pd.col("a") == 1, [True, False], "(col('a') == 1)"),
(np.log(pd.col("a")), [0.0, 0.6931471805599453], "log(col('a'))"),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

log is dangerous to use in a test because the floating point value could be different on different platforms.

Maybe use np.min() instead.

Copy link
Member Author

@MarcoGorelli MarcoGorelli Aug 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure, thanks! have replaced with np.power, so then we also test passing in a non-expression argument (2)

(np.divide(pd.col("a"), pd.col("a")), [1.0, 1.0], "divide(col('a'), col('a'))"),
],
)
def test_col_simple(
Expand Down
Loading