Method Chaining & pipe

Python · Reshaping & Workflow

Theory

Method chaining writes a sequence of steps as one expression, each method working on the result of the previous one, wrapped in parentheses so it can span lines: (df.query('amount > 0').assign(gst=lambda d: d['amount'] * 0.18).groupby('city', as_index=False)['gst'].sum().sort_values('gst', ascending=False)). It reads top to bottom like a SQL query and avoids a trail of temporary variables such as df2, df3 and df_final.

Inside a chain, use lambda d: ... in assign or loc so the step sees the current intermediate DataFrame rather than the original df. pipe(func, *args) lets your own functions join the chain: def add_tax(d, rate): return d.assign(tax=d['amount'] * rate), then df.pipe(add_tax, rate=0.18). This makes cleaning steps reusable and testable. Chains are easiest to debug when each step is on its own line; comment out the tail to inspect an intermediate result.

Why we use it

Long scripts that overwrite df again and again are hard to read and easy to break. A chain makes the transformation one clear pipeline, and pipe turns repeated steps into named, reusable functions.

When to use it

Use chaining for multi-step transformations that produce one result, and pipe for custom steps you reuse across datasets. Break the chain into named variables when an intermediate result is reused or needs inspection.

How it works

  1. Raw DataFrame
  2. Clean with .pipe(clean_names)
  3. Filter with .query(...)
  4. Derive with .assign(col=lambda d: ...)
  5. Summarise with .groupby(...).agg(...)
  6. Order with .sort_values(...)
  7. Final report from one expression

Syntax

(df
  .query('...')
  .assign(new=lambda d: ...)
  .groupby('key', as_index=False)
  .agg(...)
  .sort_values('col')
  .pipe(my_func, arg=1))

Example

report = (df.query('amount > 0')
            .assign(gst=lambda d: d['amount'] * 0.18)
            .groupby('city', as_index=False)['gst'].sum())

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic