pd.col, select and filter

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Method chains are the idiomatic way to write pandas pipelines, but they have always had one awkward spot: a step in the middle of a chain often needs to refer to a column of the intermediate result, which has no variable name. The usual answer was lambda df: df["a"] > 1. pandas 3.0 added pd.col, a deferred column reference that makes the same code read like pd.col("a") > 1, and pandas 3.1 added two methods that accept it, DataFrame.select and an extended DataFrame.filter.

This page targets pandas 3.1 on Python 3.13 or 3.14 and was checked in October 2026. Every example was run with Python 3.13 and pandas 3.1.0, and the output shown is real. pd.col exists since pandas 3.0, while DataFrame.select, and the cond and na arguments of DataFrame.filter, are new in 3.1; on 3.0 they do not exist. The plain selection operators these helpers build on are explained in Indexing and Selecting, and the migration summary is in What’s New in 3.x and Migrating.

All examples use a small table of marine mammals:

import warnings

import numpy as np
import pandas as pd

df = pd.DataFrame(
    {
        "name": ["beluga", "narwhal", "orca", "dolphin"],
        "speed": [100, 110, 56, 60],
        "length": [4.5, 4.0, 7.0, 2.5],
        "tag": [None, "rare", "common", None],
    }
)
print(df)
      name  speed  length     tag
0   beluga    100     4.5     NaN
1  narwhal    110     4.0    rare
2     orca     56     7.0  common
3  dolphin     60     2.5     NaN

What pd.col returns

pd.col("speed") does not look anything up. It returns an Expression object (the class lives in pandas.api.typing) that records what you want to do. The expression is evaluated later, when you hand it to a pandas method that accepts expressions, and it is evaluated against the DataFrame that method is working on.

c = pd.col("speed")
print(type(c))
print(repr(c))
print(repr(pd.col("speed") * 2 + pd.col("length")))
print(repr(pd.col("name").str.title()))
<class 'pandas.api.typing.Expression'>
col('speed')
(col('speed') * 2) + col('length')
col('name').str.title()

The printed form is the operation tree. Every operator and every method call you apply to an expression returns another expression, so a whole computation is built without touching any data.

flowchart LR A["pd.col speed, compared with 90"] --> B["Expression: col speed greater than 90"] B --> C["df.loc[expression]"] D["DataFrame at that point of the chain"] --> C C --> E["Expression evaluated on the DataFrame"] E --> F["Boolean Series"] F --> G["Rows kept"]

The consequence of deferred evaluation is that the same expression can be reused on different frames, and that it always sees the frame at the point where it is used. In a chain, that is the result of the previous step, not the original variable.

Where expressions can be used

The Expression documentation says they are intended for expression-based APIs: any place that accepts a callable such as lambda df: df[name] can also accept pd.col(name). In pandas 3.1 the places that this page tested are:

Method What the expression does

DataFrame.assign(new=expr)

Computes the new column

DataFrame.loc[expr]

The expression must evaluate to a boolean mask, used as the row selector

DataFrame.select(*args, **kwargs)

Picks existing columns and computes new ones (3.1)

DataFrame.filter(expr)

A boolean row mask, only with axis=0 (3.1)

They are not accepted as an argument to groupby, sort_values or drop, see What does not work.

assign

out = df.assign(
    title=pd.col("name").str.title(),
    ratio=pd.col("speed") / pd.col("length"),
    fast=pd.col("speed") > 90,
    neg=-pd.col("speed"),
    rev=100 - pd.col("speed"),
    sq=pd.col("speed") ** 2,
)
print(out.drop(columns=["tag"]).to_string())
      name  speed  length    title      ratio   fast  neg  rev     sq
0   beluga    100     4.5   Beluga  22.222222   True -100    0  10000
1  narwhal    110     4.0  Narwhal  27.500000   True -110  -10  12100
2     orca     56     7.0     Orca   8.000000  False  -56   44   3136
3  dolphin     60     2.5  Dolphin  24.000000  False  -60   40   3600

Arithmetic (addition, subtraction, multiplication, division, floor division, modulo and power), comparisons, unary minus and the reflected forms (100 - pd.col("speed")) all work. Because assign evaluates its keyword arguments in order, a later one can refer to a column created by an earlier one, with or without pd.col.

loc

In loc an expression must produce a boolean mask. Combine expressions with &, | and ~, as you would combine masks:

print(df.loc[(pd.col("speed") > 50) & (pd.col("length") < 5)])
print(df.loc[(pd.col("speed") > 100) | pd.col("name").str.startswith("o")])
print(df.loc[~(pd.col("speed") > 100), "name"].tolist())
print(df.loc[pd.col("tag").notna(), ["name", "tag"]])
      name  speed  length   tag
0   beluga    100     4.5   NaN
1  narwhal    110     4.0  rare
3  dolphin     60     2.5   NaN
      name  speed  length     tag
1  narwhal    110     4.0    rare
2     orca     56     7.0  common
['beluga', 'orca', 'dolphin']
      name     tag
1  narwhal    rare
2     orca  common

The &, | and ~ operators are the only logical operators; and, or and not ask for the truth value of the expression and raise TypeError: boolean value of an expression is ambiguous, exactly like they do for a Series. A column assignment through loc works too, with the expression as the row selector:

d = df.copy()
d.loc[pd.col("speed") > 100, "length"] = 0.0
print(d["length"].tolist())
[4.5, 0.0, 7.0, 2.5]

Everything a Series can do, deferred

The Expression documentation states that attribute access is deferred too: any method or attribute of the object the expression evaluates to can be used, including the str and dt accessors, NumPy ufuncs, indexing and the boolean operators. An unsupported attribute fails only when the expression is evaluated.

out = df.assign(
    upper=pd.col("name").str.upper(),
    nchar=pd.col("name").str.len(),
    rank=pd.col("speed").rank(),
    cum=pd.col("speed").cumsum(),
    z=(pd.col("speed") - pd.col("speed").mean()) / pd.col("speed").std(),
    tag=pd.col("tag").fillna("none"),
    capped=pd.col("speed").clip(lower=60, upper=100),
    big=pd.col("speed").where(pd.col("speed") > 60, 0),
    f=pd.col("speed").astype("float64"),
    log=np.log(pd.col("speed")),
)
print(out.drop(columns=["name", "length"]).round(3).to_string())
   speed     tag    upper  nchar  rank  cum      z  capped  big      f    log
0    100    none   BELUGA      6   3.0  100  0.673     100  100  100.0  4.605
1    110    rare  NARWHAL      7   4.0  210  1.037     100  110  110.0  4.700
2     56  common     ORCA      4   1.0  266 -0.928      60    0   56.0  4.025
3     60    none  DOLPHIN      7   2.0  326 -0.782      60    0   60.0  4.094

Two behaviours are worth noting. An aggregate such as pd.col("speed").mean() is computed on the whole column at evaluation time, which is what makes the z-score above work. And the pd.col("speed") of a datetime column offers .dt in the same way:

dates = pd.DataFrame({"seen": pd.to_datetime(["2026-01-05", "2026-03-17", "2026-07-30"])})
print(dates.assign(year=pd.col("seen").dt.year, month=pd.col("seen").dt.month_name()))
        seen  year    month
0 2026-01-05  2026  January
1 2026-03-17  2026    March
2 2026-07-30  2026     July

Conditional columns with case_when

Expression.case_when is the deferred form of Series.case_when. It takes a list of (condition, replacement) pairs, where each part can itself be an expression. Rows that match no condition keep their original value, so the result can mix types:

size = pd.col("length").case_when(
    [(pd.col("length") > 6, "large"), (pd.col("length") > 3, "medium")]
)
print(df.assign(size=size)[["name", "length", "size"]])
      name  length    size
0   beluga     4.5  medium
1  narwhal     4.0  medium
2     orca     7.0   large
3  dolphin     2.5     2.5

The unmatched dolphin row kept 2.5. Add a final catch-all condition such as (pd.col("length") > 0, "small") when every row must get a label.

Reusing and naming expressions

An expression is an ordinary Python object, so a filter you use twice can be named:

fast = pd.col("speed") > 90
print(df.loc[fast, "name"].tolist())
print(df.assign(is_fast=fast)["is_fast"].tolist())
['beluga', 'narwhal']
[True, True, False, False]

Column names that are not strings or contain spaces work, because pd.col takes any hashable column label:

odd = pd.DataFrame({0: [1, 2], "a b": [3, 4]})
print(odd.assign(z=pd.col(0) + pd.col("a b")))
   0  a b  z
0  1    3  4
1  2    4  6

Referring to a column that does not exist raises a ValueError at evaluation time that lists the available columns:

try:
    df.assign(a=pd.col("nope") + 1)
except ValueError as e:
    print(e)
Column 'nope' not found in given DataFrame.

Hint: did you mean one of ['name', 'speed', 'length', 'tag'] instead?

DataFrame.select (new in 3.1)

DataFrame.select returns a new DataFrame containing the columns you name, in the order you name them. Items can be labels, pd.col expressions, or keyword arguments that compute a new column. A keyword value is resolved like an assign value: callables and expressions are evaluated on the frame, other values are assigned as they are.

print(df.select("name", "speed"))
print(df.select(["tag", "name"]))
print(df.select("name", kmh=pd.col("speed") * 1.6, upper=pd.col("name").str.upper()))
      name  speed
0   beluga    100
1  narwhal    110
2     orca     56
3  dolphin     60
      tag     name
0     NaN   beluga
1    rare  narwhal
2  common     orca
3     NaN  dolphin
      name    kmh    upper
0   beluga  160.0   BELUGA
1  narwhal  176.0  NARWHAL
2     orca   89.6     ORCA
3  dolphin   96.0  DOLPHIN

An expression that evaluates to a Series must be named. A positional expression keeps the name of the underlying column, and .rename(...) names the result of an unnamed one:

print(df.select("name", pd.col("speed")).columns.tolist())
print(df.select((pd.col("speed") * 2).rename("double")))
try:
    df.select(pd.col("speed") * 2)
except Exception as e:
    print(type(e).__name__, "|", str(e)[:120])
['name', 'speed']
   double
0     200
1     220
2     112
3     120

Items are resolved in order and computed columns become available to later items, as in assign. A name that is requested twice is returned twice, and a computed column that has the same name as an existing one replaces it only for later items, not for a column already selected:

print(df.select("speed", speed=pd.col("speed") * 10, again=pd.col("speed")).to_string())
print(df.select("name", "name").columns.tolist())
   speed  speed  again
0    100   1000   1000
1    110   1100   1100
2     56    560    560
3     60    600    600
['name', 'name']

A single list may be given, but it cannot be mixed with further positional arguments; unpack the list instead, and a missing label raises KeyError:

cols = ["name", "speed"]
print(df.select(*cols, "length").columns.tolist())
try:
    df.select("name", ["speed"])
except TypeError as e:
    print("TypeError |", str(e)[:100])
try:
    df.select("nope")
except KeyError as e:
    print("KeyError |", e)
['name', 'speed', 'length']
TypeError | `select` supports individual columns `df.select('col1', 'col2', ...)` or a single list `df.select(['
KeyError | "None of [Index(['nope'], dtype='str')] are in the [columns]"

select always returns a DataFrame, even for a single column, so df.select("age") has one column and df["age"] is a Series.

With a MultiIndex on the columns a non-tuple label selects a whole first level, tuples select across levels, and computed columns must have full-length tuple names, which means only positional expressions renamed to a tuple are allowed:

mi = pd.DataFrame(
    np.arange(6).reshape(2, 3),
    columns=pd.MultiIndex.from_tuples([("a", "x"), ("a", "y"), ("b", "x")]),
)
print(mi.select("a"))
print(mi.select(("a", "y"), ("b", "x")))
print(mi.select(("a", "y"), pd.col(("a", "x")).rename(("c", "z"))))
   a
   x  y
0  0  1
1  3  4
   a  b
   y  x
0  1  2
1  4  5
   a  c
   y  z
0  1  0
1  4  3

select compared with other ways to pick columns

Tool Strength Limitation

df[["a", "b"]]

Shortest for a fixed list of existing columns

Cannot compute columns; the brackets also mean rows in other forms

df.loc[:, ["a", "b"]]

Labels, slices and masks on columns, and assignment

Cannot compute columns

df.select("a", c=pd.col("b") * 2)

Pick and compute in one step, results ordered as written

New in 3.1; always returns a DataFrame

df.select_dtypes(include="number")

Choose columns by dtype

Does not pick by name

df.filter(regex="^a", axis=1)

Choose columns by name pattern

The like, regex and items forms are documented as going to be deprecated

DataFrame.filter (extended in 3.1)

Before 3.1, DataFrame.filter only selected labels, with items, like or regex, and its name misled many people into expecting a row filter by value. In 3.1 it gained a boolean mask path:

  • cond= takes a boolean Series, array, callable or expression. A Series is aligned on the labels of the filtered axis; any other array-like must have the same length as that axis.

  • The first positional argument is a boolean mask only when it is a callable or an expression. Any other positional value, including a list of booleans, is a list of labels (and a list of booleans emits a UserWarning, because it was probably meant as a mask).

  • na= says how to treat missing values in the mask: False (the default), True, or "raise" to raise a ValueError.

  • An expression is only supported with axis=0; axis=1 raises a ValueError.

  • The positional argument and items, cond, like and regex are mutually exclusive.

print(df.filter(pd.col("speed") > 60))
print(df.filter(lambda d: d["speed"] > 60).index.tolist())
print(df.filter(cond=df["speed"] > 60).index.tolist())
      name  speed  length   tag
0   beluga    100     4.5   NaN
1  narwhal    110     4.0  rare
[0, 1]
[0, 1]

Missing values in a nullable boolean mask need a decision:

m = pd.Series([True, None, False, True], dtype="boolean")
print(df.filter(cond=m).index.tolist())               # NA treated as False
print(df.filter(cond=m, na=True).index.tolist())      # NA kept
try:
    df.filter(cond=m, na="raise")
except ValueError as e:
    print("ValueError |", e)
[0, 3]
[0, 1, 3]
ValueError | The mask contains missing values

The label forms still work and do not warn in 3.1, but the documentation says that items, like and regex will be deprecated in a future version and recommends DataFrame.select, loc, or filter with a callable instead:

print(df.filter(items=["name", "speed"]).columns.tolist())
print(df.filter(regex="^s", axis=1).columns.tolist())
print(df.filter(like="e", axis=1).columns.tolist())
print(df.filter(like="o", axis=0).index.tolist())   # axis=0 matches the row labels
['name', 'speed']
['speed']
['name', 'speed', 'length']
[]

Passing a list of booleans positionally selects labels, not rows, which is almost never what you want:

with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    r = df.filter([True, False, True, False])
    print(r.shape, w[0].category.__name__)
(4, 0) UserWarning

The empty result has the four row labels but no columns, because none of the column names equals True or False. Use cond=[True, False, True, False] for a mask.

A complete method chain

The helpers combine into a pipeline with no lambda and no temporary variable:

result = (
    df
    .assign(kmh=pd.col("speed") * 1.6)
    .filter(pd.col("kmh") > 100)
    .select("name", "kmh")
    .sort_values("kmh", ascending=False)
)
print(result)
      name    kmh
1  narwhal  176.0
0   beluga  160.0

Compared with the older idioms, the same filter can be written as follows. All of them give identical results; they differ in readability inside a chain and in when the column is looked up.

Form Notes

df.loc[df["speed"] > 60]

Needs the variable name; breaks in a chain where the frame has changed

df.loc[lambda d: d["speed"] > 60]

Works in a chain; more punctuation

df.loc[pd.col("speed") > 60]

Works in a chain; one name per column; 3.0 and later

df.query(speed  60)

Compact string syntax; @variable for outer names; harder to refactor and to type-check

df.filter(pd.col("speed") > 60)

Same as loc with a mask, as a method; 3.1 and later

What does not work

Expressions are a young feature, and in pandas 3.1 some places do not accept them:

checks = {
    "sort_values": lambda: df.sort_values(pd.col("speed")),
    "groupby": lambda: df.groupby(pd.col("tag")).size(),
    "drop": lambda: df.drop(columns=pd.col("speed")),
    "filter axis=1": lambda: df.filter(pd.col("speed") > 60, axis=1),
}
for name, f in checks.items():
    try:
        f()
    except Exception as e:
        print(f"{name}: {type(e).__name__} | {str(e)[:80]}")
sort_values: KeyError | col('speed')
groupby: TypeError | boolean value of an expression is ambiguous
drop: TypeError | unhashable type: 'Expression'
filter axis=1: ValueError | Expressions such as pd.col(...) are only supported by DataFrame.filter with axis

Use a column name in those methods, or compute the column first with assign.

Also remember the general limits:

  • An expression is not a value: you cannot print its result, index it into a Python list, or use it in if, and, or or not.

  • It needs a DataFrame to evaluate against, so it is only useful in methods that accept it.

  • Adding a column with assign to a DataFrame whose columns are a MultiIndex, using a name that is not a full-length tuple, emits a Pandas4Warning saying a future version will raise; use select with a renamed tuple, or set the column through df[("top", "sub")] = ....

  • pandas 3.0 has pd.col in assign and loc, but not select, filter(expr) or filter(cond=...).

Choosing between a lambda and pd.col

  • Prefer pd.col for simple column references and arithmetic: it reads in order and has no closure over a loop variable, a classic lambda bug.

  • Keep a lambda or a named function when the logic does not fit an expression, for example a Python function applied row by row (see User-Defined Functions), or when you still support pandas 2.x.

  • Prefer loc and a mask for assignment, as in Indexing and Selecting.