Python / Data Science Essentials Interview Questions
What is Pandas method chaining and how does df.pipe() support it?
Method chaining is the style of writing data transformations as a single expression where each step's result is the input to the next. It avoids creating intermediate variables, reads like a pipeline, and makes the data flow explicit from top to bottom.
import pandas as pd
# --- Without chaining (intermediate variables) ---
df1 = pd.read_csv('raw.csv')
df2 = df1.dropna(subset=['revenue'])
df3 = df2.rename(columns={'rev': 'revenue'})
df4 = df3[df3['revenue'] > 0]
df5 = df4.assign(log_revenue=lambda d: d['revenue'].apply(np.log1p))
result = df5.groupby('region')['log_revenue'].mean()
# --- With method chaining ---
import numpy as np
result = (
pd.read_csv('raw.csv')
.dropna(subset=['revenue'])
.rename(columns={'rev': 'revenue'})
.query('revenue > 0')
.assign(log_revenue=lambda d: np.log1p(d['revenue']))
.groupby('region')['log_revenue']
.mean()
)
# --- df.pipe() for custom functions ---
def remove_outliers(df, col, n_std=3):
mean, std = df[col].mean(), df[col].std()
return df[(df[col] - mean).abs() < n_std * std]
def add_rank(df, col):
df = df.copy()
df['rank'] = df[col].rank(ascending=False)
return df
result = (
pd.read_csv('raw.csv')
.pipe(remove_outliers, col='revenue')
.pipe(add_rank, col='revenue')
)
# pipe passes the DataFrame as the first argument to the functiondf.pipe(func, *args, **kwargs) calls func(df, *args, **kwargs), inserting the DataFrame at the front of the argument list. This lets you write standalone functions and use them inline in a method chain without breaking the fluent style.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
