ZetCode

Pandas Method Chaining

last modified November 17, 2026 Python 3.15

A data-cleaning script often applies a long series of small transformations: filter some rows, add a column, change a type, summarise the result. One way to write that is to save each intermediate result in its own variable. Another is to connect the operations with dots, so each result flows directly into the next call.

Method chaining is exactly that: a chain of method calls where the object returned by one call becomes the object the next call works on. The chain reads from top to bottom like a recipe, keeps the original DataFrame untouched, and avoids a pile of temporary names.

A first chain: loc and assign

Most Pandas transformations return a new DataFrame, which is what makes chaining possible. Here we first select rows with loc, a method that chooses rows and columns by label or by a Boolean condition, and then add a column with assign. The expression inside assign uses a lambda, a small anonymous function, so it can refer to the DataFrame being built.

chain_loc_assign.py
import pandas as pd

df = pd.DataFrame({'name': ['a', 'b', 'c'], 'price': [10, 25, 40]})
result = (df
          .loc[df['price'] > 15]
          .assign(taxed=lambda d: d['price'] * 1.1))
print(result)

The row for a is dropped by loc, and the remaining rows gain a taxed column holding the price plus ten percent. The original df is unchanged; result is a new DataFrame. Wrapping the chain in parentheses lets us spread it over several readable lines.

$ python chain_loc_assign.py
  name  price  taxed
1    b     25   27.5
2    c     40   44.0

Adding columns with assign

The assign method returns a copy of the DataFrame with new columns added or existing ones replaced. Passing several keyword arguments adds several columns at once. Because the original is never modified, chaining assign calls is safe: each step simply builds on the previous result.

chain_assign.py
import pandas as pd

df = pd.DataFrame({'price': [10, 20, 30], 'qty': [1, 2, 3]})
out = df.assign(subtotal=lambda d: d['price'] * d['qty'],
                doubled=lambda d: d['price'] * 2)
print(out)

Two new columns appear: subtotal multiplies price by quantity and doubled doubles the price. Both lambdas receive the same intermediate DataFrame, so the order in which the keywords are written does not matter here.

$ python chain_assign.py
   price  qty  subtotal  doubled
0     10    1        10       20
1     20    2        40       40
2     30    3        90       60

Changing types inside a chain

The astype method converts a column to a different data type. This often needs to happen early, before arithmetic can be done on values that arrived as text. Because astype also returns a new DataFrame, it slots naturally into a chain followed by assign.

chain_astype.py
import pandas as pd

df = pd.DataFrame({'id': [1, 2, 3], 'score': ['10', '20', '30']})
out = (df
       .astype({'score': 'int64'})
       .assign(score_doubled=lambda d: d['score'] * 2))
print(out)
print()
print(out.dtypes)

The score column starts out holding strings. After astype it holds 64-bit integers, which is why multiplying it by two now produces numbers rather than repeated text; the check of the dtypes property confirms that all three columns are integers. A string version would have produced the text twice instead.

$ python chain_astype.py
   id  score  score_doubled
0   1     10             20
1   2     20             40
2   3     30             60

id               int64
score            int64
score_doubled    int64
dtype: object

Ending a chain with groupby

A groupby splits rows into groups sharing a value, applies a calculation to each group and combines the results. It works well at the end of a chain: build the column you want to summarise, then group and reduce. The example below reads as a single pipeline from raw rows to a summary.

chain_groupby.py
import pandas as pd

df = pd.DataFrame({
    'region': ['North', 'South', 'North', 'South'],
    'price': [10, 20, 30, 40],
    'qty': [1, 2, 3, 4]
})
result = (df
          .assign(total=lambda d: d['price'] * d['qty'])
          .groupby('region')['total']
          .sum())
print(result)

First a total column is computed for every row, then those totals are added up per region. North contributes 10 plus 90, and South contributes 20 plus 160, giving 100 and 200. The result is indexed by the group names, a form covered in more depth in the Pandas grouping data tutorial.

$ python chain_groupby.py
region
North    100
South    200
Name: total, dtype: int64

Reusable steps with pipe

A chain can only call Pandas' own methods unless we bring our own functions into it. The pipe method does that: it passes the current DataFrame as the first argument to a function and uses whatever that function returns as the next value in the chain. It is the idiomatic way to keep custom steps reusable without breaking the flow.

chain_pipe.py
import pandas as pd

def add_total(df):
    return df.assign(total=df['price'] * df['qty'])

def keep_expensive(df):
    return df[df['total'] >= 40]

df = pd.DataFrame({'price': [10, 20, 30], 'qty': [1, 2, 3]})
result = df.pipe(add_total).pipe(keep_expensive)
print(result)

The first function adds a total column and the second keeps only rows whose total is at least 40. Each function can be tested and reused on its own, yet the main line still reads as a short chain. Notice that the second function relies on a column created by the first, so their order matters.

$ python chain_pipe.py
   price  qty  total
1     20    2     40
2     30    3     90

Local display settings with option_context

Pandas has global display options, such as how many decimal places to show. Changing them once with set_option affects the rest of the program, which is rarely what we want inside one example. The option_context context manager applies a setting only inside its with block and restores the previous value afterwards.

chain_options.py
import pandas as pd

df = pd.DataFrame({'value': [1.23456, 2.34567]})
with pd.option_context('display.precision', 2):
    print('inside context:')
    print(df)
print('outside context:')
print(df)

Inside the block the numbers are rounded to two decimal places for display; outside it the default precision is back, so all five decimal places are shown again. Only printing changed: the underlying values are identical. This is a convenient companion to a chain when you want one tidy view of an intermediate result.

$ python chain_options.py
inside context:
   value
0   1.23
1   2.35
outside context:
     value
0  1.23456
1  2.34567

When intermediate variables are clearer

Chaining is a style choice, not a rule. A short chain that flows in one direction is usually easier to read than a stack of names such as df2, df3 and df4. Long chains are harder: if the result goes wrong it is awkward to inspect the middle, and a step reused in two places cannot be copied without duplicating code. In those cases, give the intermediate result a meaningful name, or lift the step into a function and call it with pipe.

A practical guideline is to chain while each step is obvious on its own line, and to break the chain at the moment a name would help a reader understand what that intermediate table represents. Debugging is another good reason to stop: a named variable can be printed or checked with an assertion before the next step runs. See the Pandas options tutorial for more on display settings and apply, map and transform for other ways to add derived columns.

Source

Pandas DataFrame.assign Documentation, Pandas DataFrame.pipe Documentation, Pandas DataFrame.astype Documentation, and Pandas option_context Documentation

In this article we have chained loc, assign, astype and groupby into readable pipelines, added our own steps with pipe, scoped display settings with option_context, and discussed when a named intermediate variable is the clearer choice. For selecting rows see the Pandas loc tutorial, and for the grouping step see Pandas grouping data.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pandas tutorials.