🐍 Python for Everyone

← Back to challenges

Chapter 24 Interview Prep 55 min read

Interview Questions: Pandas for Data Analysis

pandas comes up in nearly every data analyst, data scientist, and backend-with-reporting interview. This set covers DataFrames vs. NumPy arrays, creating DataFrames, inspecting data, selecting/filtering, the .loc[]/.iloc[] distinction, missing data, and groupby aggregation.

1 What's the difference between a pandas DataFrame and a NumPy array?

A NumPy array is homogeneous — every element shares one fixed dtype, and it has no concept of column names. A DataFrame is a labeled 2D table where each column can hold a different dtype (text, numbers, dates), and every row and column has a label, not just a numeric position. Internally, each DataFrame column is backed by its own NumPy array, so pandas gets NumPy's speed while adding labeling and mixed column types on top.

Describing them as interchangeable, or not knowing that a DataFrame column is itself a NumPy array underneath.

"When would you use a plain NumPy array instead of a DataFrame?" (When data is genuinely uniform and numeric with no meaningful column labels — a math-heavy grid or matrix — rather than tabular business data.)

2 What is a Series, and how does it relate to a DataFrame?

A Series is one labeled 1D column of data. A DataFrame is a table made of one or more Series sharing the same row index. Pulling a single column out of a DataFrame with df['col'] returns a Series; pulling multiple columns with df[['col1','col2']] returns a DataFrame, even for a single-item list.

Not knowing that single vs. double brackets change the return type (Series vs. DataFrame) on the exact same underlying data.

"What type does df[['revenue']] return, with just one column name in a list?" (A DataFrame with one column — the double-bracket list syntax always returns a DataFrame, regardless of how many names are in the list.)

3 Why would you use pd.read_csv() instead of Python's built-in csv module?

read_csv() replaces the entire manual open-file/loop-rows/parse-values pattern with one function call, returning a full DataFrame with types already inferred. Follow-up analysis — sums, filters, grouping — then uses one-line column and DataFrame methods instead of hand-written accumulator loops. The csv module is still the right tool for line-by-line streaming or writing custom row formats; read_csv() is the right tool the moment the goal is analysis, not just reading.

Claiming the csv module is now useless — it isn't, it's just solving a different problem (raw row access vs. tabular analysis).

"What does read_csv() do automatically that the csv module doesn't?" (Type inference per column — numbers become int64/float64 automatically, rather than every field arriving as a string that needs manual int()/float() conversion.)

4 What do .head(), .info(), and .describe() each tell you about a DataFrame?

.head(n) previews the first n rows — a fast sanity check that the data loaded correctly. .info() summarizes column names, non-null counts, and dtypes in one call, the fastest way to spot missing data or a column that loaded as the wrong type. .describe() computes count/mean/std/min/max/quartiles for every numeric column, giving a quick sense of the data's actual distribution.

Confusing .info() with .describe() — one is structural (columns, types, nulls), the other is statistical (numeric summaries).

"You load a CSV and revenue is showing up as text instead of numbers. Which method would reveal this fastest?" (.info() — it shows the dtype of every column in one summary, including a text/object dtype where a number was expected.)

5 How does boolean filtering work on a DataFrame?

A comparison like df['revenue'] > 1000 produces a Series of True/False values, one per row. Using that boolean Series as an index — df[df['revenue'] > 1000] — keeps only the rows where it's True. It's the direct DataFrame equivalent of NumPy's array boolean masking, just filtering whole rows instead of individual array elements.

Reaching for a manual for-loop with an if-check to filter rows, missing that this is a one-line, no-loop idiom.

"How would you combine two conditions, like revenue over 1000 AND region equal to East?" (Use & with each condition parenthesized: df[(df['revenue'] > 1000) & (df['region'] == 'East')] — same & / | convention as NumPy, not Python's and/or keywords.)

6 What's the difference between .loc[] and .iloc[], and why does it matter?

.loc[] selects by label — the actual row index value or column name, whatever it is. .iloc[] selects by integer position, counting from 0, regardless of what the labels actually are. They happen to agree on a freshly loaded DataFrame with the default 0,1,2,... index, which is exactly why the distinction is easy to overlook — until the index becomes something else (a product name, a date, or rows that have been filtered or sorted so their positions no longer match their original labels), at which point using the wrong one silently returns the wrong row instead of raising an error.

Claiming .loc[] and .iloc[] are interchangeable, or not recognizing that mixing them up fails silently rather than with a clear error.

"After filtering a DataFrame with a boolean condition, why might .iloc[0] and .loc[0] now return different rows?" (Filtering keeps the original row labels but the positions shift — the first remaining row keeps its old label, e.g. 3, but is now at position 0, so .iloc[0] finds it while .loc[0] looks for a row still labeled 0, which may no longer exist or may be a completely different row.)

7 How does pandas represent missing data, and what tools handle it?

Missing values show up as NaN ("Not a Number"). .isna() returns a same-shape True/False DataFrame showing exactly which cells are missing. .dropna() removes rows containing any missing value. .fillna(value) replaces missing values with a chosen default — a fixed value, or per-column via a dict, or something computed like a column's own mean.

Trying to check for missing data with == NaN directly — NaN == NaN is False, which is exactly why .isna() exists as a dedicated method.

"Why might dropping every row with any missing value be a bad default choice?" (It can discard otherwise-useful rows — a real sale record missing only its region field still has valid revenue data worth keeping; fillna() with a sensible default often preserves more of the dataset.)

8 Why does a numeric column sometimes display with decimals (like 1200.0) after loading data with missing values?

NaN is technically a float value, and a single pandas column can only hold one dtype. If any value in an otherwise-integer column is missing, pandas can't keep the column as int64 (since int64 has no way to represent NaN), so it silently upgrades the entire column to float64 — even the values that were originally whole numbers.

Assuming this is a bug or a display quirk rather than a direct consequence of NaN's type and the one-dtype-per-column rule.

"How would you get that column back to whole-number display after filling in the missing values?" (Fill the missing values first with .fillna(), then convert with .astype(int) — once there's no NaN left, the column can safely hold an integer dtype again.)

9 Walk through what groupby() actually does, conceptually.

groupby() follows a split-apply-combine pattern: split the DataFrame into groups based on unique values in the given column, apply an aggregate function (sum, mean, etc.) independently to each group, then combine the per-group results back into one output. Nothing is actually computed at the groupby() call itself — the split only becomes concrete once an aggregate method is called on the grouped object.

Describing groupby() as if it immediately returns a result on its own, without recognizing an aggregate call is required to actually produce output.

"How would you group by two columns at once, like region and product?" (df.groupby(['region', 'product'])['revenue'].sum() — groups by every unique combination of the two columns, giving a more finely broken-down result than grouping by one column alone.)

10 What's the difference between .sum()/.mean() and .agg() after a groupby()?

.sum()/.mean() apply one single aggregate function to every group. .agg({'col': ['sum', 'mean']}) generalizes this to multiple statistics on the same column (or different statistics per column) in one call, returning a result with each requested statistic as its own column.

Not knowing .agg() can take a dict to apply different aggregate functions to different columns simultaneously.

"How would you get both the sum and count of revenue per product in one call?" (df.groupby('product')['revenue'].agg(['sum', 'count']) — passing a list of function names when working with a single already-selected column.)

11 How would you build a "top N" report — e.g. the top 3 products by revenue?

Group by the category column, aggregate the metric (typically sum), sort the result descending with .sort_values(ascending=False), then take the first N rows with .head(n). For example: df.groupby('product')['revenue'].sum().sort_values(ascending=False).head(3). This chains three ideas from the chapter — groupby, sort_values, and head — into the exact shape of a real business report.

Reaching for a manual loop and manual max-tracking instead of the chained groupby/sort_values/head pipeline.

"What would change if you wanted the 3 worst-performing products instead?" (Drop ascending=False, since sort_values() defaults to ascending order, then .head(3) — the smallest values now come first.)

12 When would you reach for pandas instead of plain NumPy, and vice versa?

Reach for pandas when data has meaningful column labels, mixed types across columns, or naturally comes from a spreadsheet/CSV/database table — which covers most real business and reporting data. Reach for plain NumPy when data is genuinely uniform and numeric, especially for heavier math (linear algebra, image arrays, simulations) where the extra labeling overhead of a DataFrame isn't needed.

Treating pandas as a strict, universal upgrade over NumPy rather than a specialized tool built on top of it for a specific (very common) kind of data.

"Is a DataFrame column ever passed directly into a function expecting a NumPy array?" (Yes — most NumPy functions accept a pandas Series directly since it's backed by a NumPy array internally, and .to_numpy()/.values converts explicitly when a pure array is required.)

13 How would you add a new computed column to a DataFrame?

Assign to a new column name directly: df['revenue'] = df['units_sold'] * df['unit_price']. This runs vectorized across every row at once, the same as any other pandas/NumPy arithmetic — no explicit loop needed, and the new column is added in place on the existing DataFrame.

Reaching for a manual row-by-row loop with .loc[] assignments to build the new column, missing the direct vectorized assignment.

"What if the new column depends on a condition, like a discount only for revenue over 1000?" (np.where(df['revenue'] > 1000, df['revenue'] * 0.9, df['revenue']) is the common vectorized pattern — conditional element-wise selection without a Python-level loop.)

14 Why does pandas remain fast even though it adds labels and mixed types on top of NumPy?

Each individual DataFrame column is still backed by its own contiguous, single-dtype NumPy array — the labeling and the "table of mixed-type columns" structure exist at the DataFrame level, wrapping several homogeneous NumPy arrays underneath. So operations within a single column (a sum, a filter, a groupby aggregate) still run as fast, vectorized NumPy operations; the label bookkeeping pandas adds on top is a comparatively small overhead.

Believing pandas reimplements its own math engine from scratch, rather than delegating the actual numeric work to NumPy underneath.

"Does that mean a DataFrame with 10 columns is really 10 separate NumPy arrays?" (Conceptually yes, one homogeneous array per column, all sharing the same row index/labels — which is exactly why one column can be int64, the next str, and the next float64, unlike a single NumPy array.)

Rapid-Fire Review

Quick recall check — fill in each blank and hit Check.

🎉 Perfect score — you're ready to talk about this chapter in an interview.
← Challenges Build the Project →