Expr
class Expr
Categories: tableframe
A lazy column expression evaluated against a TableFrame.
Create expressions with col / lit from
tabsdatak.tableframe.functions and pass them to a frame's
select, filter, with_columns or group_by().agg.
Operators are element-wise; reducers (sum, mean, min ...)
collapse a group. Date/time and string helpers live under dt and
str.
Examples
tf.with_columns((col("a") * 2).alias("doubled"))
tf.group_by("g").agg(col("a").sum().alias("total"))
Properties
Methods
sqrtdef sqrt() -> Expr
Square root of each element.
Example:
tf.select(col("v").sqrt().alias("root"))
cbrtdef cbrt() -> Expr
Cube root of each element.
Example:
tf.select(col("v").cbrt().alias("root"))
log10def log10() -> Expr
Base-10 logarithm of each element.
Example:
tf.select(col("v").log10().alias("magnitude"))
expdef exp() -> Expr
Exponential (e raised to each element).
Example:
tf.select(col("v").exp().alias("growth"))
aliasdef alias(name: Any) -> Expr
Rename the output column of this expression.
Parameters:
nameAnyNew column name. Must be a valid identifier (letters, digits, underscores; starting with a letter or underscore) up to 100 characters.
Example:
tf.select(col("a").alias("identifier"))
An expression keeps no name of its own, so alias every computed column:
tf.with_columns((col("a") * 2).alias("doubled"))
not_def not_() -> Expr
Logical negation of a boolean expression.
Example:
tf.filter(col("flag").not_())
is_nulldef is_null() -> Expr
Return whether each element is null.
Example:
tf.filter(col("v").is_null())
is_not_nulldef is_not_null() -> Expr
Return whether each element is not null.
Example:
tf.filter(col("v").is_not_null())
is_finitedef is_finite() -> Expr
Return whether each floating-point element is finite.
Example:
tf.filter(col("v").is_finite())
is_infinitedef is_infinite() -> Expr
Return whether each floating-point element is infinite.
Example:
tf.filter(col("v").is_infinite())
is_nandef is_nan() -> Expr
Return whether each floating-point element is NaN.
Example:
tf.filter(col("v").is_nan())
is_not_nandef is_not_nan() -> Expr
Return whether each floating-point element is not NaN.
Example:
tf.filter(col("v").is_not_nan())
countdef count() -> Expr
Count the non-null elements in the group; see len.
Example:
tf.group_by("g").agg(col("v").count().alias("filled"))
lendef len() -> Expr
Count all rows in the group, including nulls; see count.
Example:
tf.group_by("g").agg(col("v").len().alias("rows"))
slicedef slice(offset: int | Expr, length: int | Expr | None = None) -> Expr
Take a contiguous slice of the column's values.
Parameters:
Example:
tf.select(col("a").slice(1, 2))
A negative offset counts from the end:
tf.select(col("a").slice(-2)) # the last two values
floordef floor() -> Expr
Round each element down to the nearest integer.
Example:
tf.select(col("v").floor().alias("floor"))
ceildef ceil() -> Expr
Round each element up to the nearest integer.
Example:
tf.select(col("v").ceil().alias("ceil"))
rounddef round(decimals: int = 0, mode: RoundMode = 'half_to_even') -> Expr
Round floating-point elements to a number of decimals.
Parameters:
modeRoundMode (Literal['half_to_even', 'half_away_from_zero', 'to_zero'])Tie-breaking rule, one of half_to_even,
half_away_from_zero or to_zero.
Example:
tf.select(col("v").round(2).alias("rounded"))
round_sig_figsdef round_sig_figs(digits: int) -> Expr
Round elements to a number of significant figures.
Parameters:
Example:
tf.select(col("v").round_sig_figs(2).alias("approx"))
castdef cast(
dtype: PolarsDataType | type[Any],
*,
strict: bool = True,
wrap_numerical: bool = False,
) -> Expr
Cast the expression to a different data type.
Parameters:
Target data type (e.g. pl.Int64, pl.Float64,
pl.String).
strictboolIf True, raise on values that do not fit the
target; if False, set them to null instead.
Example:
tf.select(col("a").cast(Float64))
With strict=False an unconvertible value becomes null instead of raising:
tf.select(col("name").cast(Int64, strict=False))
fill_nulldef fill_null(
value: Any | Expr | None = None,
strategy: FillNullStrategy | None = None,
limit: int | None = None,
) -> Expr
Replace null values with a value or a fill strategy.
Pass either value or strategy, not both.
Parameters:
strategyFillNullStrategy | None (Literal['forward', 'backward', 'min', 'max', 'mean', 'zero', 'one'] | None)Fill strategy instead of value: one of
forward, backward, min, max, mean,
zero or one.
Example:
tf.with_columns(col("v").fill_null(0.0))
A strategy fills from the neighbouring rows instead of a constant:
tf.sort("id").with_columns(col("v").fill_null(strategy="forward"))
fill_nanmaxdef max() -> Expr
Return the maximum element in the group.
Example:
tf.group_by("g").agg(col("a").max().alias("largest"))
mindef min() -> Expr
Return the minimum element in the group.
Example:
tf.group_by("g").agg(col("a").min().alias("smallest"))
sumdef sum() -> Expr
Return the sum of the elements in the group.
Example:
tf.group_by("g").agg(col("a").sum().alias("total"))
meandef mean() -> Expr
Return the mean of the elements in the group.
Example:
tf.group_by("g").agg(col("a").mean().alias("average"))
mediandef median() -> Expr
Return the median of the elements in the group.
Example:
tf.group_by("g").agg(col("a").median().alias("middle"))
n_uniquedef n_unique() -> Expr
Count the distinct elements in the group.
Example:
tf.group_by("g").agg(col("a").n_unique().alias("distinct"))
firstdef first(*, ignore_nulls: bool = False) -> Expr
Return the first element in the group.
Parameters:
Example:
tf.sort("id").group_by("g").agg(col("a").first().alias("earliest"))
lastdef last(*, ignore_nulls: bool = False) -> Expr
Return the last element in the group.
Parameters:
Example:
tf.sort("id").group_by("g").agg(col("a").last().alias("latest"))
is_uniquedef is_unique() -> Expr
Return whether each element occurs only once in the column.
Example:
tf.filter(col("g").is_unique())
filterdef filter(
*predicates: IntoExprColumn | Iterable[IntoExprColumn] = (),
**constraints: Any = {},
) -> Expr
Keep only the values that satisfy the given predicates.
Values whose predicate is not True (including null) are
dropped. Typically used inside an aggregation.
Parameters:
Boolean expressions to apply.
Example:
tf.group_by("g").agg(
col("a").filter(col("a") > 1).sum().alias("big_total"),
)
and_def and_(*others: Any = ()) -> Expr
Bitwise and with the given expressions (integer or boolean).
Parameters:
Example:
tf.filter(col("flag").and_(col("a") > 2))
or_def or_(*others: Any = ()) -> Expr
Bitwise or with the given expressions (integer or boolean).
Parameters:
Example:
tf.filter(col("flag").or_(col("a") > 3))
eqdef eq(other: Any) -> Expr
Element-wise equality, equivalent to expr == other.
Parameters:
otherAnyValue or expression to compare against. A null on
either side yields null; use eq_missing to treat two
nulls as equal.
Example:
tf.filter(col("g").eq("x"))
eq_missingdef eq_missing(other: Any) -> Expr
Element-wise equality where two nulls compare as equal.
Parameters:
Example:
tf.select(col("v").eq(None).alias("eq")) # null everywhere
tf.select(col("v").eq_missing(None).alias("eq_missing")) # True on nulls
gedef ge(other: Any) -> Expr
Element-wise greater-than-or-equal, like expr >= other.
Parameters:
Example:
tf.filter(col("a").ge(2))
gtdef gt(other: Any) -> Expr
Element-wise greater-than, like expr > other.
Parameters:
Example:
tf.filter(col("a").gt(2))
ledef le(other: Any) -> Expr
Element-wise less-than-or-equal, like expr <= other.
Parameters:
Example:
tf.filter(col("a").le(2))
ltdef lt(other: Any) -> Expr
Element-wise less-than, like expr < other.
Parameters:
Example:
tf.filter(col("a").lt(2))
nedef ne(other: Any) -> Expr
Element-wise inequality, equivalent to expr != other.
Parameters:
otherAnyValue or expression to compare against. A null on
either side yields null; use ne_missing to treat two
nulls as equal.
Example:
tf.filter(col("g").ne("x"))
ne_missingdef ne_missing(other: Any) -> Expr
Element-wise inequality where two nulls compare as equal.
Parameters:
Example:
tf.select(col("v").ne_missing(None).alias("filled"))
adddef add(other: Any) -> Expr
Add other; for strings, concatenate. Same as +.
Parameters:
Example:
tf.with_columns(col("a").add(1).alias("next"))
floordivdef floordiv(other: Any) -> Expr
Floor division by other. Same as //.
Parameters:
Example:
tf.select(col("a").floordiv(2).alias("halved"))
moddef mod(other: Any) -> Expr
Modulo (remainder) by other. Same as %.
Parameters:
Example:
tf.select(col("a").mod(2).alias("parity"))
muldef mul(other: Any) -> Expr
Multiply by other. Same as *.
Parameters:
Example:
tf.with_columns(col("a").mul(10).alias("scaled"))
subdef sub(other: Any) -> Expr
Subtract other. Same as -.
Parameters:
Example:
tf.with_columns(col("b").sub(col("a")).alias("gap"))
negdef neg() -> Expr
Unary negation of each element. Same as unary -.
Example:
tf.select(col("a").neg().alias("negated"))
truedivdef truediv(other: Any) -> Expr
True (floating-point) division by other. Same as /.
Parameters:
Example:
tf.select(col("b").truediv(col("a")).alias("ratio"))
powxordef xor(other: Any) -> Expr
Bitwise xor with other (integer or boolean). Same as ^.
Parameters:
Example:
tf.select(col("flag").xor(True).alias("toggled"))
is_indef is_in(other: Expr | Collection[Any], *, nulls_equal: bool = False) -> Expr
Return whether each element is contained in other.
Parameters:
Example:
tf.filter(col("g").is_in(["x", "y"]))
is_betweendef is_between(
lower_bound: IntoExpr,
upper_bound: IntoExpr,
closed: ClosedInterval = 'both',
) -> Expr
Return whether each element lies between two bounds.
Parameters:
lower_boundIntoExpr (int | float | Decimal | date | time | datetime | timedelta | str | bool | bytes | list[Any] | Expr | str | None)Lower bound value or expression.
upper_boundIntoExpr (int | float | Decimal | date | time | datetime | timedelta | str | bool | bytes | list[Any] | Expr | str | None)Upper bound value or expression.
closedClosedInterval (Literal['left', 'right', 'both', 'none'])Which ends are inclusive: both (default),
left, right or none.
Example:
tf.filter(col("a").is_between(2, 4))
Both bounds are inclusive by default; closed narrows them:
tf.filter(col("a").is_between(2, 4, closed="left"))
hashdef hash(
seed: int = 0,
seed_1: int | None = None,
seed_2: int | None = None,
seed_3: int | None = None,
) -> Expr
Hash each element to a 64-bit unsigned integer.
Parameters:
Example:
tf.select(col("email").hash().alias("fingerprint"))
reinterpretdef reinterpret(
*,
signed: bool | None = None,
dtype: PolarsDataType | None = None,
) -> Expr
Reinterpret a 64-bit integer's bits as another integer type.
Reinterprets the raw bits (no value conversion); for a real
conversion use cast. Only valid on 64-bit integer columns.
Parameters:
dtypePolarsDataType | None (DataType | None)Explicit target integer type; overrides signed.
Example:
tf.select(col("a").reinterpret(signed=False).alias("bits"))
absdef abs() -> Expr
Absolute value of each element.
Example:
tf.select(col("v").abs().alias("size"))
rankdef rank(
method: RankMethod = 'average',
*,
descending: bool = False,
seed: int | None = None,
) -> Expr
Assign a rank to each element within the column.
Parameters:
methodRankMethod (Literal['average', 'min', 'max', 'dense', 'ordinal', 'random'])Tie-handling method: average (default), min,
max, dense, ordinal or random.
Example:
tf.with_columns(col("a").rank().alias("position"))
method decides how ties are resolved, and descending ranks the largest value first:
tf.with_columns(col("a").rank("dense", descending=True).alias("place"))
diffdef diff(n: int | IntoExpr = 1, null_behavior: NullBehavior = 'ignore') -> Expr
Difference between each element and one n rows away.
Works on numeric and temporal columns. Order-dependent, so sort first for a deterministic result.
Parameters:
nint | IntoExpr (int | int | float | Decimal | date | time | datetime | timedelta | str | bool | bytes | list[Any] | Expr | str | None)Rows to look back; negative looks forward.
null_behaviorNullBehavior (Literal['ignore', 'drop'])How to handle nulls: ignore or drop.
Example:
tf.sort("id").with_columns(col("a").diff().alias("change"))
clipdef clip(
lower_bound: NumericLiteral | TemporalLiteral | IntoExprColumn | None = None,
upper_bound: NumericLiteral | TemporalLiteral | IntoExprColumn | None = None,
) -> Expr
Clamp each element to the given bounds.
Values below lower_bound become it, values above
upper_bound become it, values in range are unchanged. Provide
at least one bound.
Parameters:
lower_boundNumericLiteral | TemporalLiteral | IntoExprColumn | None (int | float | Decimal | date | time | datetime | timedelta | Expr | str | None)Minimum allowed value; None for no lower bound.
upper_boundNumericLiteral | TemporalLiteral | IntoExprColumn | None (int | float | Decimal | date | time | datetime | timedelta | Expr | str | None)Maximum allowed value; None for no upper bound.
Example:
tf.with_columns(col("a").clip(2, 3).alias("clipped"))
One bound may be omitted to clamp on a single side:
tf.with_columns(col("a").clip(lower_bound=2).alias("at_least_two"))
signdef sign() -> Expr
Return the sign of each element (-1, 0 or 1).
Example:
tf.select(col("v").sign().alias("sign"))
sindef sin() -> Expr
Sine of each element, in radians.
Example:
tf.select(col("v").sin().alias("sin"))
cosdef cos() -> Expr
Cosine of each element, in radians.
Example:
tf.select(col("v").cos().alias("cos"))
tandef tan() -> Expr
Tangent of each element, in radians.
Example:
tf.select(col("v").tan().alias("tan"))
cotdef cot() -> Expr
Cotangent of each element, in radians.
Example:
tf.select(col("v").cot().alias("cot"))
arcsindef arcsin() -> Expr
Inverse sine of each element.
Example:
tf.select(col("v").arcsin().alias("arcsin"))
arccosdef arccos() -> Expr
Inverse cosine of each element.
Example:
tf.select(col("v").arccos().alias("arccos"))
arctandef arctan() -> Expr
Inverse tangent of each element.
Example:
tf.select(col("v").arctan().alias("arctan"))
sinhdef sinh() -> Expr
Hyperbolic sine of each element.
Example:
tf.select(col("v").sinh().alias("sinh"))
coshdef cosh() -> Expr
Hyperbolic cosine of each element.
Example:
tf.select(col("v").cosh().alias("cosh"))
tanhdef tanh() -> Expr
Hyperbolic tangent of each element.
Example:
tf.select(col("v").tanh().alias("tanh"))
arcsinhdef arcsinh() -> Expr
Inverse hyperbolic sine of each element.
Example:
tf.select(col("v").arcsinh().alias("arcsinh"))
arccoshdef arccosh() -> Expr
Inverse hyperbolic cosine of each element.
Example:
tf.select(col("v").arccosh().alias("arccosh"))
arctanhdef arctanh() -> Expr
Inverse hyperbolic tangent of each element.
Example:
tf.select(col("v").arctanh().alias("arctanh"))
degreesdef degrees() -> Expr
Convert each element from radians to degrees.
Example:
tf.select(col("v").degrees().alias("degrees"))
radiansdef radians() -> Expr
Convert each element from degrees to radians.
Example:
tf.select(col("v").radians().alias("radians"))
logdef log(base: float | IntoExpr = 2.718281828459045) -> Expr
Logarithm of each element to the given base.
Parameters:
basefloat | IntoExpr (float | int | float | Decimal | date | time | datetime | timedelta | str | bool | bytes | list[Any] | Expr | str | None)Logarithm base; defaults to e (natural logarithm).
Example:
tf.select(col("v").log().alias("ln"))
Pass a base for a logarithm other than the natural one:
tf.select(col("v").log(2).alias("log2"))
log1pdef log1p() -> Expr
Natural logarithm of 1 + element.
Example:
tf.select(col("v").log1p().alias("log1p"))