Python / Data Science Essentials Interview Questions
How do you quickly extract top/bottom rows and random samples from a Pandas DataFrame?
During EDA you often need to inspect extremes (the highest-revenue customers, the worst-performing products) or draw a random sample for quick analysis. Pandas provides concise methods for each of these.
import pandas as pd
import numpy as np
rng = np.random.default_rng(42)
df = pd.DataFrame({
'product': [f'P{i}' for i in range(100)],
'revenue': rng.integers(1_000, 100_000, 100),
'returns': rng.integers(0, 500, 100),
})
# --- Top and bottom N rows ---
df.nlargest(5, 'revenue') # 5 highest revenue products
df.nsmallest(5, 'revenue') # 5 lowest revenue products
# Multiple columns — break ties by second column
df.nlargest(5, ['revenue', 'returns'])
# --- Random sampling ---
df.sample(n=10, random_state=42) # 10 random rows
df.sample(frac=0.1, random_state=42) # 10% of rows
df.sample(n=10, replace=True) # with replacement (bootstrapping)
# Stratified sample — same proportion from each category
df['tier'] = pd.cut(df['revenue'], bins=3, labels=['low','mid','high'])
stratified = df.groupby('tier', group_keys=False).apply(
lambda g: g.sample(frac=0.1, random_state=42)
)
# --- Head, tail, every Nth row ---
df.head(10) # first 10 rows
df.tail(10) # last 10 rows
df.iloc[::5] # every 5th row — useful for large datasetsnlargest and nsmallest are significantly faster than sort_values(...).head(n) for large DataFrames because they use a partial sort (heap) under the hood — O(N log k) instead of O(N log N) for the full sort. Use them whenever you only need the extremes, not a fully sorted result.
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...
