PrepStack › AI › Python for Data (NumPy, Pandas)

Python for Data (NumPy, Pandas) interview cheat sheet

ndarrays, broadcasting, vectorisation, DataFrames, groupby, joins and cleaning

Data, ML and analytics interviews use NumPy and pandas as the shared language. Interviewers check that you think in whole arrays, not loops: shapes, axes and broadcasting in NumPy, then indexing, missing data, groupby, joins and reshaping in pandas. Senior rounds add memory, copy semantics (pandas 3.0 Copy-on-Write) and when to reach for Polars. Library snippets are illustrative; the standard-library snippets show the same ideas from scratch and are executed. Read the 15-minute list, then quiz yourself.

15-minute revision

  1. NumPy is fast because an ndarray is one contiguous typed buffer and loops run in compiled C (vectorisation). A Python list is an array of pointers to boxed objects.
  2. An array is a buffer plus metadata: dtype, shape, strides (bytes to step per axis) and ndim. reshape, .T and basic slices only change metadata, so they are views.
  3. Basic slicing (a[1:5], a[:, 0]) returns a view. Fancy (a[[0, 2]]) and boolean (a[a > 0]) indexing always return a copy. Check with np.shares_memory.
  4. ravel() returns a view when it can; flatten() always copies. reshape(-1, 3) lets NumPy infer one dimension.
  5. Broadcasting: align shapes from the right; two dims are compatible if equal or one of them is 1. (3, 1) + (4,) gives (3, 4).
  6. axis=0 collapses rows (one result per column); axis=1 collapses columns (one result per row). Use keepdims=True to keep the result broadcastable.
  7. Use rng = np.random.default_rng(seed) (the Generator API), not the legacy global np.random.seed.
  8. * is element-wise; @ / np.matmul is matrix product. np.dot equals @ for 2-D but differs for N-D and allows scalars.
  9. A Series is a 1-D labelled array; a DataFrame is a dict of Series sharing one index. Arithmetic aligns on labels, not position.
  10. loc is label-based and its slices include the end; iloc is position-based and excludes the end. Combine filters with &, |, ~ and parentheses.
  11. isna / fillna / dropna / ffill. NaN != NaN. An int column with a missing value becomes float64 unless you use nullable Int64.
  12. Prefer vectorised ops > Series.map (lookups) > apply (row-wise Python loop, slow). np.where / np.select replace most row-wise if logic.
  13. groupby is split-apply-combine: agg reduces each group to one row, transform returns a same-length result, filter drops whole groups.
  14. merge joins on columns (how = inner, left, right, outer, cross); join joins on the index; concat stacks. Use validate= and indicator=True to catch bad keys.
  15. pandas 3.0 (January 2026): Copy-on-Write is always on, SettingWithCopyWarning is gone, chained assignment never works, and strings default to the new str dtype.
  16. Memory: load only needed usecols, set dtypes, use category for low-cardinality text, read big CSVs with chunksize, store as Parquet (columnar, typed, compressed).

NumPy foundations

Why NumPy: contiguous memory & vectorisation

A typed, contiguous buffer plus loops in C makes NumPy 10–100× faster than Python loops for numeric work.

  • A Python list stores pointers to separate heap objects. Each int is a full object (about 28 bytes) with a type pointer and refcount.
  • An ndarray stores raw values of one dtype side by side in one block. int64 uses exactly 8 bytes per value, and CPU caches and SIMD work well on it.
  • Vectorisation means expressing work as whole-array operations (a * 2 + b). The loop still exists, but it runs in compiled C, with no per-element type checks or interpreter overhead.
  • Each operation creates a temporary array, so long expressions use extra memory. Use in-place ops (a *= 2) or out= when memory matters.
  • NumPy is the base layer for pandas, scikit-learn, SciPy and most ML libraries. They all speak the array protocol and share buffers without copying.

Interview questions

  • Why is NumPy faster than a Python list?
  • What does “vectorisation” mean in NumPy?
  • When would a Python list still be the better choice?

ndarray anatomy & creation functions

An ndarray is a data buffer plus dtype, shape, strides and ndim. Creation functions build arrays without Python loops.

  • shape is a tuple of sizes per axis; ndim is len(shape); size is the element count; nbytes = size * itemsize.
  • strides is the number of bytes to move to reach the next element along each axis. A C-ordered (3, 4) int64 array has strides (32, 8).
  • dtype is fixed for the whole array. Mixing types upcasts: np.array([1, 2.5]) is float64; adding a string gives a Unicode dtype.
  • Default memory order is C (row-major): the last axis changes fastest. Fortran order (order='F') makes the first axis fastest.
  • np.empty does not initialise memory, so it contains garbage. Use it only when you will overwrite every value.

Interview questions

  • What are shape, ndim, dtype and strides?
  • Why do strides matter?
  • Difference between np.arange and np.linspace?

Indexing & slicing: views vs copies, boolean & fancy

Basic slices are views that share memory. Boolean masks and integer-array (fancy) indexing always make copies.

  • Basic indexing uses integers, slices, ... and np.newaxis. The result is a view, so writing to it changes the original.
  • Boolean indexing (a[a > 5]) picks elements where the mask is True and returns a flattened copy.
  • Fancy indexing (a[[0, 2, 2]]) picks by integer arrays, allows repeats and reorders, and returns a copy.
  • Assignment through any index writes into the original: a[a < 0] = 0 modifies a in place, even though reading a[a < 0] gives a copy.
  • Multi-dimensional: m[1] is a row, m[:, 1] is a column, and m[[0, 2], [1, 3]] picks the pairs (0, 1) and (2, 3), not a sub-grid. Use np.ix_ for a grid.
  • Use np.shares_memory(a, b) or check b.base is a to confirm whether something is a view.

Interview questions

  • Difference between a view and a copy in NumPy?
  • Why does a[a > 0] = 0 change a when a[a > 0] returns a copy?
  • What is fancy indexing?

reshape, ravel, flatten & new axes

Reshaping changes how a buffer is viewed. It is free when the memory layout allows it and copies otherwise.

  • reshape(new_shape) needs the same total size. Use -1 for one dimension to let NumPy infer it: a.reshape(-1, 3).
  • ravel() returns a flat view when the array is contiguous, otherwise a copy. flatten() always copies.
  • a[:, np.newaxis] (or a[:, None]) turns shape (n,) into (n, 1). np.expand_dims and squeeze add and remove size-1 axes.
  • transpose / .T reverses axes; swapaxes and moveaxis move specific axes. These are views.
  • Stacking: np.vstack, np.hstack, np.stack (adds a new axis) and np.concatenate(axis=...) all copy into a new array.

Interview questions

  • Difference between ravel() and flatten()?
  • What does -1 mean in reshape?
  • How do you turn a 1-D array into a column vector?

NumPy computation

Broadcasting rules

Broadcasting lets arrays of different shapes combine by virtually stretching size-1 axes, without copying data.

  • Rule 1: line the shapes up from the right; pad the shorter shape with 1s on the left.
  • Rule 2: two dimensions are compatible if they are equal or one of them is 1. Otherwise NumPy raises ValueError: operands could not be broadcast together.
  • Rule 3: the result size on each axis is the larger of the two. A size-1 axis is repeated using stride 0, so no memory is copied.
  • Typical uses: subtract column means X - X.mean(axis=0), scale rows with X / X.sum(axis=1, keepdims=True), and build outer products and pairwise distances.
  • Pairwise trick: P[:, None, :] - P[None, :, :] turns (n, d) into (n, n, d). It is quick, but memory grows as n², so chunk it for large n.

Interview questions

  • Explain NumPy broadcasting rules.
  • Why does X - X.mean(axis=1) fail for a (100, 3) array, and how do you fix it?
  • What is the memory risk of broadcasting?

ufuncs, aggregations & axis

Universal functions apply element-wise in C; reductions like sum and mean collapse the axis you name.

  • A ufunc (np.add, np.exp, np.maximum, comparison operators) works element-wise, broadcasts, and supports out=, where= and dtype=.
  • Ufuncs have methods: np.add.reduce (sum), np.add.accumulate (cumsum), np.multiply.outer, and np.add.at for unbuffered repeated-index updates.
  • axis=0 reduces down the rows and gives one value per column. axis=1 reduces across columns and gives one value per row. axis=None reduces everything.
  • keepdims=True keeps the reduced axis as size 1, so the result broadcasts back against the input.
  • NaN spreads through sum and mean. Use np.nansum, np.nanmean and friends, or mask first.
  • np.where(cond, a, b) is a vectorised if/else; np.argmax / np.argsort return indices, not values.

Interview questions

  • What is a ufunc?
  • What does axis=0 mean for a 2-D array?
  • Difference between np.max and np.maximum?

Random numbers, seeds & linear algebra

Use a seeded Generator for reproducible randomness, and @ for matrix products. * is element-wise.

  • Modern API: rng = np.random.default_rng(42), then rng.integers, rng.random, rng.normal, rng.choice, rng.permutation, rng.shuffle. The default bit generator is PCG64.
  • The legacy np.random.seed / np.random.rand use one global state. It is shared by every library and not thread-safe to reason about. Pass a Generator around instead.
  • For parallel work, derive independent streams with rng.spawn(n) or np.random.SeedSequence(seed).spawn(n), not seeds like seed + i.
  • A * B is element-wise; A @ B (np.matmul) is the matrix product. For 2-D arrays np.dot(A, B) is the same as A @ B.
  • matmul treats N-D inputs as stacks of matrices and does not accept scalars; dot does a sum-product over the last axis of a and the second-to-last of b, and accepts scalars.
  • np.linalg: inv, solve, det, eig, svd, norm, lstsq. Prefer solve(A, b) to inv(A) @ b: it is faster and more numerically stable.

Interview questions

  • How do you make NumPy randomness reproducible?
  • Difference between np.dot, np.matmul (@) and *?
  • Why prefer np.linalg.solve(A, b) over np.linalg.inv(A) @ b?

pandas core

Series vs DataFrame & the index

A Series is a labelled 1-D array; a DataFrame is a table of Series that share one index. Operations align on labels.

  • A Series = values (a NumPy or Arrow array) + an index + a name. A DataFrame = columns of possibly different dtypes + a row index + column labels.
  • df['col'] returns a Series; df[['col']] returns a one-column DataFrame.
  • The index gives labels for fast lookup and automatic alignment: s1 + s2 matches labels, and labels missing on either side give NaN.
  • Index labels do not have to be unique, but duplicates make loc return several rows and can break reindex and joins.
  • set_index('id') moves a column into the index; reset_index() moves it back. A MultiIndex gives hierarchical labels (often from groupby on several keys).
  • Exploration: head, info (dtypes and non-null counts), describe, shape, dtypes, value_counts, nunique.

Interview questions

  • Difference between a Series and a DataFrame?
  • What is the index for, and what is index alignment?
  • What is a MultiIndex?

loc vs iloc, selection & filtering

loc selects by label and includes the slice end; iloc selects by integer position and excludes it.

  • df.loc[rows, cols] uses labels and boolean masks. Label slices are inclusive: df.loc['a':'c'] includes 'c'.
  • df.iloc[rows, cols] uses positions like Python lists. df.iloc[0:2] returns rows 0 and 1.
  • df.at[label, col] and df.iat[i, j] are fast scalar accessors.
  • Filter with boolean masks: df[(df.age > 30) & (df.city == 'NY')]. Each condition needs parentheses and you must use &, |, ~.
  • Helpers: isin, between (inclusive on both ends by default), str.contains, query('age > 30 and city == "NY"').
  • To set values on filtered rows, do it in one loc call: df.loc[df.age > 30, 'senior'] = True.

Interview questions

  • Difference between loc and iloc?
  • Why do you need & and parentheses instead of and when filtering?
  • How do you update a column only for rows that match a condition?

Missing data: isna, fillna, dropna

Detect with isna, then either drop, fill or impute, and watch how missing values change dtypes.

  • pandas uses NaN for floats, NaT for datetimes, None/NaN for object and string columns, and pd.NA for nullable extension dtypes (Int64, boolean, string).
  • NaN != NaN, so never test with ==. Use isna() / notna(); df.isna().sum() counts missing values per column.
  • dropna() drops rows with any missing value; use subset=[...], how='all' or thresh=n to control it.
  • fillna(value) accepts a scalar or a dict per column. ffill() / bfill() carry values forward or back; interpolate() fills numerically.
  • An integer column with a missing value becomes float64 by default. Use the nullable Int64 dtype to keep integers.
  • Aggregations skip NaN by default (skipna=True), so mean divides by the count of non-missing values.

Interview questions

  • How do you handle missing values in pandas?
  • Difference between NaN, None and pd.NA?
  • Why did my integer column turn into float?

dtypes, categoricals & string ops

The right dtype saves memory and prevents bugs. Use category for repeated labels and the .str accessor for vectorised text work.

  • Common dtypes: int64, float64, bool, datetime64, timedelta64, category, object, the nullable Int64/boolean, and Arrow-backed types.
  • pandas 3.0 infers text columns as the new str dtype (Arrow-backed when pyarrow is installed, else NumPy object). Code that checks dtype == object needs updating.
  • Convert with astype, pd.to_numeric(errors='coerce') (bad values become NaN), pd.to_datetime and convert_dtypes().
  • category stores each distinct value once plus small integer codes. It is great for low-cardinality text (country, status) and speeds up groupby and sorting.
  • Ordered categoricals (pd.CategoricalDtype([...], ordered=True)) support comparisons and sort in business order, like low < mid < high.
  • The .str accessor vectorises string methods: lower, strip, contains, replace, split(expand=True), extract (regex groups), len, startswith.

Interview questions

  • When would you use the category dtype?
  • What changed for strings in pandas 3.0?
  • How do you clean a numeric column that contains junk text?

Vectorised ops vs apply vs map

Vectorised column maths is fastest; map is for lookups; apply is a Python loop and should be the last resort.

  • Vectorised: df.price * df.qty, np.log(df.x), .str and .dt methods. They run in C over whole columns.
  • Series.map maps each value through a dict, Series or function. It is ideal for recoding; unmapped keys become NaN.
  • Series.apply(func) calls a Python function per element. DataFrame.apply(func, axis=1) calls it per row and builds a Series for each row, which is very slow.
  • DataFrame.map(func) is element-wise over every cell. It replaced applymap, which pandas 3.0 removed.
  • Replace row-wise if/else with np.where, np.select, Series.where/mask, pd.cut (bins) or clip.
  • Rough speed order: vectorised ≫ map with dict > apply per element > apply(axis=1) > iterrows.

Interview questions

  • Difference between map, apply and DataFrame.map (formerly applymap)?
  • Why is df.apply(f, axis=1) slow and what do you use instead?
  • You need tiered discounts based on amount. How do you do it without a loop?

Grouping, joining & reshaping

groupby: split-apply-combine, agg & transform

Split rows by keys, apply a function to each group, and combine the results. Choose agg, transform or filter by the output shape you need.

  • Split rows into groups by one or more keys, apply a function to each group, combine the results into a new object.
  • agg reduces each group to one row. Use named aggregation: agg(total=('pts', 'sum'), n=('pts', 'size')).
  • transform returns a result the same length as the input, aligned to the original rows. Use it for share-of-group, group-mean imputation and z-scores within a group.
  • filter keeps or drops whole groups (lambda g: len(g) > 2). apply is the flexible, slow fallback.
  • Group keys become the index; pass as_index=False or call reset_index() to keep them as columns. size() counts rows including NaN; count() counts non-null values.
  • Built-in names ('sum', 'mean', 'max') use fast Cython paths. Python lambdas are much slower. NaN keys are dropped unless dropna=False.

Interview questions

  • Explain split-apply-combine.
  • Difference between agg and transform?
  • Difference between size() and count() in groupby?
  • How do you fill missing values with the group mean?

merge, join & concat

merge is a SQL-style join on columns, join is a merge on the index, and concat stacks objects along an axis.

  • pd.merge(left, right, on='key', how=...): inner (matches only, the default), left, right, outer (all keys) and cross (Cartesian product).
  • Use left_on / right_on for different column names and suffixes=('_l', '_r') for clashing columns.
  • Duplicate keys multiply rows: a key appearing 2 times on the left and 3 on the right gives 6 rows. Guard with validate='one_to_one' or 'many_to_one'.
  • indicator=True adds a _merge column (left_only, right_only, both). That is the standard way to write an anti-join.
  • df.join(other) joins on the index (left join by default). pd.concat([a, b]) stacks rows; axis=1 aligns side by side on the index; ignore_index=True renumbers rows.
  • pd.merge_asof joins on the nearest key (for example, the latest price at or before each trade time); both sides must be sorted on that key.

Interview questions

  • Difference between merge, join and concat?
  • Explain inner, left, right and outer joins.
  • My row count went up after a left join. Why, and how do you prevent it?
  • How do you do an anti-join in pandas?

pivot, pivot_table, melt, sorting & ranking

pivot and pivot_table go long to wide, melt goes wide to long, and sort_values / rank / nlargest order the data.

  • pivot(index, columns, values) only reshapes; it raises an error on duplicate index/column pairs.
  • pivot_table reshapes and aggregates duplicates (aggfunc='mean' by default), with fill_value and margins=True for totals.
  • melt(id_vars, value_vars, var_name, value_name) turns columns into rows (wide to long), which is the tidy format for plotting and groupby.
  • stack / unstack move a level between the columns and the index. pd.crosstab(a, b) builds a frequency table.
  • sort_values(['team', 'pts'], ascending=[True, False]) sorts by several keys. sort_index sorts by labels. nlargest(n, 'col') is faster than a full sort for top-N.
  • rank(method=...): average (default), min (SQL RANK), dense (SQL DENSE_RANK), first (ROW_NUMBER by order of appearance), max.

Interview questions

  • Difference between pivot and pivot_table?
  • What does melt do and when do you need it?
  • How do you reproduce SQL RANK and DENSE_RANK in pandas?

Datetime, resample & rolling windows

Parse to datetime64, put time in the index, then use resample for calendar buckets and rolling for moving windows.

  • pd.to_datetime(col, format=..., errors='coerce') parses strings; an explicit format is faster and avoids day/month guessing.
  • The .dt accessor: year, month, day_name(), floor('h'), tz_localize('UTC'), tz_convert('Asia/Kolkata').
  • resample(rule) is a time-based groupby on a DatetimeIndex: 'D', 'W', 'ME' (month end), 'QE', 'YE', 'h', 'min'. pandas 3.0 removed the old 'M', 'Q', 'Y' aliases.
  • rolling(window) is a moving window: a count (rolling(7)) or a time span (rolling('7D'), which handles gaps). min_periods controls when output starts.
  • expanding() is a cumulative window; ewm(span=...) is an exponentially weighted mean. shift, diff and pct_change compare with earlier rows.
  • pandas 3.0 infers the datetime resolution (for example datetime64[us] when parsing strings) instead of always using nanoseconds.

Interview questions

  • Difference between resample and rolling?
  • How do you compute a 7-day rolling average when some days have no data?
  • How do you compute month-over-month growth?

Performance & production

CSV/Parquet I/O, memory optimisation & chunking

Read only what you need with the right dtypes, use Parquet for storage, and stream big files in chunks.

  • read_csv options that matter: usecols, dtype, parse_dates, nrows, chunksize, na_values, and engine='pyarrow' for faster parsing.
  • Parquet is columnar, typed, compressed (snappy by default) and supports column selection and filter pushdown. It needs pyarrow (or fastparquet).
  • df.memory_usage(deep=True) shows the true size, including string contents. Text columns are usually the biggest cost.
  • Shrink memory by downcasting (pd.to_numeric(col, downcast='integer')), category for repeated strings, Arrow-backed strings, and dropping unused columns early.
  • Chunking: for chunk in pd.read_csv(path, chunksize=100_000) processes a file larger than RAM; aggregate each chunk and combine the partial results.
  • Beyond one machine's memory, consider DuckDB, Polars (lazy and streaming), Dask or Spark rather than pushing pandas further.

Interview questions

  • A 10 GB CSV does not fit in memory. What do you do?
  • Why is Parquet preferred over CSV for analytics?
  • How do you reduce a DataFrame's memory usage?

SettingWithCopyWarning & Copy-on-Write (pandas 3.0)

In pandas 3.0 every derived object behaves like a copy. Chained assignment never works, and the old warning is gone.

  • Before 3.0, whether df[mask] or df['col'] returned a view or a copy depended on internals. Writing to it might or might not change df, so pandas raised SettingWithCopyWarning.
  • Copy-on-Write (CoW) is the only mode in pandas 3.0 (released January 2026): any indexing result or method output behaves as a copy. To change a DataFrame you must modify that DataFrame directly.
  • Chained assignment like df['a'][0] = 1 or df[df.x > 0]['y'] = 1 never updates df in 3.0. Use df.loc[0, 'a'] = 1 or df.loc[df.x > 0, 'y'] = 1.
  • SettingWithCopyWarning was removed, and defensive .copy() calls are no longer needed to silence it.
  • Under the hood pandas still shares memory lazily; the real copy happens only when one side is written (copy on write). This makes many methods faster.
  • Arrays from to_numpy() / .values may be read-only views under CoW; call .copy() before writing to them. The mode.copy_on_write option no longer has any effect.

Interview questions

  • What is SettingWithCopyWarning and why did it happen?
  • What is Copy-on-Write in pandas 3.0?
  • What breaks when moving from pandas 2.x to 3.0?

pandas vs Polars

Polars is a Rust, Arrow-based, multi-threaded DataFrame library with a lazy query optimiser; pandas has the broadest ecosystem.

  • Polars is written in Rust on Apache Arrow memory. It uses all CPU cores by default and has no row index.
  • Its expression API (pl.col('x').sum()) lets the engine plan and parallelise work. Lazy mode (scan_parquet, .lazy() ... .collect()) adds query optimisation: predicate and projection pushdown, and common sub-plan elimination.
  • Polars has a streaming engine for data larger than memory, and strict schemas; it distinguishes null (missing) from NaN (a float value).
  • pandas wins on ecosystem and familiarity: scikit-learn, statsmodels, plotting, many tutorials, and the index model for time series and alignment.
  • pandas 3.0 narrows some gaps with Arrow-backed strings, Copy-on-Write and the new pd.col() expressions, but execution is still mostly single-threaded and eager.
  • Interoperability is cheap through Arrow: pl.from_pandas(df) and pl_df.to_pandas().

Interview questions

  • When would you choose Polars over pandas?
  • What does lazy evaluation give you in Polars?
  • Name three behavioural differences that bite people when switching from pandas to Polars.

Common interview tasks

Top-N per group, dedupe, forward fill, percent of total and ranking come up again and again. Know the one-line pandas idiom for each.

  • Top-N per group: df.sort_values('amt', ascending=False).groupby('g').head(n), or nlargest per group. Use rank to handle ties explicitly.
  • Dedupe: drop_duplicates(subset=['user'], keep='last'). For “latest record per user”, sort by time first; duplicated() gives a mask to inspect.
  • Forward fill per group: df.groupby('id')['price'].ffill(), so values do not leak between entities.
  • Percent of total: x / x.sum() overall, x / df.groupby('g')['x'].transform('sum') per group.
  • Second highest / Nth value: s.drop_duplicates().nlargest(2).iloc[-1], or a dense rank equal to 2.
  • Also common: first purchase per user (groupby().min() / idxmin), sessionisation (ts.diff() > gap then cumsum), cumulative totals (groupby().cumsum()), and year-over-year growth (pct_change).

Interview questions

  • How do you get the top 3 products by revenue in each category?
  • How do you keep only the latest record per customer?
  • How do you forward-fill sensor readings without leaking values across sensors?
  • How would you split user events into sessions with a 30-minute inactivity gap?