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
- NumPy is fast because an
ndarrayis one contiguous typed buffer and loops run in compiled C (vectorisation). A Python list is an array of pointers to boxed objects. - An array is a buffer plus metadata:
dtype,shape,strides(bytes to step per axis) andndim.reshape,.Tand basic slices only change metadata, so they are views. - 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 withnp.shares_memory. ravel()returns a view when it can;flatten()always copies.reshape(-1, 3)lets NumPy infer one dimension.- Broadcasting: align shapes from the right; two dims are compatible if equal or one of them is 1.
(3, 1) + (4,)gives(3, 4). axis=0collapses rows (one result per column);axis=1collapses columns (one result per row). Usekeepdims=Trueto keep the result broadcastable.- Use
rng = np.random.default_rng(seed)(theGeneratorAPI), not the legacy globalnp.random.seed. *is element-wise;@/np.matmulis matrix product.np.dotequals@for 2-D but differs for N-D and allows scalars.- A Series is a 1-D labelled array; a DataFrame is a dict of Series sharing one index. Arithmetic aligns on labels, not position.
locis label-based and its slices include the end;ilocis position-based and excludes the end. Combine filters with&,|,~and parentheses.isna/fillna/dropna/ffill.NaN != NaN. An int column with a missing value becomesfloat64unless you use nullableInt64.- Prefer vectorised ops >
Series.map(lookups) >apply(row-wise Python loop, slow).np.where/np.selectreplace most row-wiseiflogic. groupbyis split-apply-combine:aggreduces each group to one row,transformreturns a same-length result,filterdrops whole groups.mergejoins on columns (how= inner, left, right, outer, cross);joinjoins on the index;concatstacks. Usevalidate=andindicator=Trueto catch bad keys.- pandas 3.0 (January 2026): Copy-on-Write is always on,
SettingWithCopyWarningis gone, chained assignment never works, and strings default to the newstrdtype. - Memory: load only needed
usecols, setdtypes, usecategoryfor low-cardinality text, read big CSVs withchunksize, 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
liststores pointers to separate heap objects. Eachintis a full object (about 28 bytes) with a type pointer and refcount. - An
ndarraystores raw values of one dtype side by side in one block.int64uses 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) orout=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.
shapeis a tuple of sizes per axis;ndimislen(shape);sizeis the element count;nbytes = size * itemsize.stridesis 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).dtypeis fixed for the whole array. Mixing types upcasts:np.array([1, 2.5])isfloat64; 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.emptydoes not initialise memory, so it contains garbage. Use it only when you will overwrite every value.
Interview questions
- What are
shape,ndim,dtypeandstrides? - Why do strides matter?
- Difference between
np.arangeandnp.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,
...andnp.newaxis. The result is a view, so writing to it changes the original. - Boolean indexing (
a[a > 5]) picks elements where the mask isTrueand 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] = 0modifiesain place, even though readinga[a < 0]gives a copy. - Multi-dimensional:
m[1]is a row,m[:, 1]is a column, andm[[0, 2], [1, 3]]picks the pairs(0, 1)and(2, 3), not a sub-grid. Usenp.ix_for a grid. - Use
np.shares_memory(a, b)or checkb.base is ato confirm whether something is a view.
Interview questions
- Difference between a view and a copy in NumPy?
- Why does
a[a > 0] = 0changeawhena[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-1for 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](ora[:, None]) turns shape(n,)into(n, 1).np.expand_dimsandsqueezeadd and remove size-1 axes.transpose/.Treverses axes;swapaxesandmoveaxismove specific axes. These are views.- Stacking:
np.vstack,np.hstack,np.stack(adds a new axis) andnp.concatenate(axis=...)all copy into a new array.
Interview questions
- Difference between
ravel()andflatten()? - What does
-1mean inreshape? - 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 withX / 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 supportsout=,where=anddtype=. - Ufuncs have methods:
np.add.reduce(sum),np.add.accumulate(cumsum),np.multiply.outer, andnp.add.atfor unbuffered repeated-index updates. axis=0reduces down the rows and gives one value per column.axis=1reduces across columns and gives one value per row.axis=Nonereduces everything.keepdims=Truekeeps the reduced axis as size 1, so the result broadcasts back against the input.- NaN spreads through
sumandmean. Usenp.nansum,np.nanmeanand friends, or mask first. np.where(cond, a, b)is a vectorised if/else;np.argmax/np.argsortreturn indices, not values.
Interview questions
- What is a ufunc?
- What does
axis=0mean for a 2-D array? - Difference between
np.maxandnp.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), thenrng.integers,rng.random,rng.normal,rng.choice,rng.permutation,rng.shuffle. The default bit generator is PCG64. - The legacy
np.random.seed/np.random.randuse one global state. It is shared by every library and not thread-safe to reason about. Pass aGeneratoraround instead. - For parallel work, derive independent streams with
rng.spawn(n)ornp.random.SeedSequence(seed).spawn(n), not seeds likeseed + i. A * Bis element-wise;A @ B(np.matmul) is the matrix product. For 2-D arraysnp.dot(A, B)is the same asA @ B.matmultreats N-D inputs as stacks of matrices and does not accept scalars;dotdoes a sum-product over the last axis ofaand the second-to-last ofb, and accepts scalars.np.linalg:inv,solve,det,eig,svd,norm,lstsq. Prefersolve(A, b)toinv(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)overnp.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 + s2matches labels, and labels missing on either side giveNaN. - Index labels do not have to be unique, but duplicates make
locreturn several rows and can breakreindexand joins. set_index('id')moves a column into the index;reset_index()moves it back. A MultiIndex gives hierarchical labels (often fromgroupbyon 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]anddf.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
loccall:df.loc[df.age > 30, 'senior'] = True.
Interview questions
- Difference between
locandiloc? - Why do you need
&and parentheses instead ofandwhen 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
NaNfor floats,NaTfor datetimes,None/NaNfor object and string columns, andpd.NAfor nullable extension dtypes (Int64,boolean,string). NaN != NaN, so never test with==. Useisna()/notna();df.isna().sum()counts missing values per column.dropna()drops rows with any missing value; usesubset=[...],how='all'orthresh=nto 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
float64by default. Use the nullableInt64dtype to keep integers. - Aggregations skip NaN by default (
skipna=True), someandivides by the count of non-missing values.
Interview questions
- How do you handle missing values in pandas?
- Difference between
NaN,Noneandpd.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 nullableInt64/boolean, and Arrow-backed types. - pandas 3.0 infers text columns as the new
strdtype (Arrow-backed whenpyarrowis installed, else NumPy object). Code that checksdtype == objectneeds updating. - Convert with
astype,pd.to_numeric(errors='coerce')(bad values become NaN),pd.to_datetimeandconvert_dtypes(). categorystores each distinct value once plus small integer codes. It is great for low-cardinality text (country, status) and speeds upgroupbyand sorting.- Ordered categoricals (
pd.CategoricalDtype([...], ordered=True)) support comparisons and sort in business order, like low < mid < high. - The
.straccessor vectorises string methods:lower,strip,contains,replace,split(expand=True),extract(regex groups),len,startswith.
Interview questions
- When would you use the
categorydtype? - 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),.strand.dtmethods. They run in C over whole columns. Series.mapmaps 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 replacedapplymap, which pandas 3.0 removed.- Replace row-wise
if/elsewithnp.where,np.select,Series.where/mask,pd.cut(bins) orclip. - Rough speed order: vectorised ≫
mapwith dict >applyper element >apply(axis=1)>iterrows.
Interview questions
- Difference between
map,applyandDataFrame.map(formerlyapplymap)? - 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.
aggreduces each group to one row. Use named aggregation:agg(total=('pts', 'sum'), n=('pts', 'size')).transformreturns 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.filterkeeps or drops whole groups (lambda g: len(g) > 2).applyis the flexible, slow fallback.- Group keys become the index; pass
as_index=Falseor callreset_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 unlessdropna=False.
Interview questions
- Explain split-apply-combine.
- Difference between
aggandtransform? - Difference between
size()andcount()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) andcross(Cartesian product).- Use
left_on/right_onfor different column names andsuffixes=('_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=Trueadds a_mergecolumn (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=1aligns side by side on the index;ignore_index=Truerenumbers rows.pd.merge_asofjoins 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,joinandconcat? - 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_tablereshapes and aggregates duplicates (aggfunc='mean'by default), withfill_valueandmargins=Truefor 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/unstackmove 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_indexsorts 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
pivotandpivot_table? - What does
meltdo and when do you need it? - How do you reproduce SQL
RANKandDENSE_RANKin 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 explicitformatis faster and avoids day/month guessing.- The
.dtaccessor: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_periodscontrols when output starts.expanding()is a cumulative window;ewm(span=...)is an exponentially weighted mean.shift,diffandpct_changecompare 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
resampleandrolling? - 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_csvoptions that matter:usecols,dtype,parse_dates,nrows,chunksize,na_values, andengine='pyarrow'for faster parsing.- Parquet is columnar, typed, compressed (snappy by default) and supports column selection and filter pushdown. It needs
pyarrow(orfastparquet). 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')),categoryfor 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]ordf['col']returned a view or a copy depended on internals. Writing to it might or might not changedf, so pandas raisedSettingWithCopyWarning. - 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] = 1ordf[df.x > 0]['y'] = 1never updatesdfin 3.0. Usedf.loc[0, 'a'] = 1ordf.loc[df.x > 0, 'y'] = 1. SettingWithCopyWarningwas 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()/.valuesmay be read-only views under CoW; call.copy()before writing to them. Themode.copy_on_writeoption no longer has any effect.
Interview questions
- What is
SettingWithCopyWarningand 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) fromNaN(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)andpl_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), ornlargestper group. Userankto 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() > gapthencumsum), 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?