📥 Download Complete 2026 Printable PDF Notes, Architecture Diagrams & GitHub Code
Get instant free access to the 2026 printable PDF cheat-sheet, runnable lab repositories, interview evaluation rubric, and AI Campus 6-Month Paid Corporate Internship roadmap.
Download Free PDF & Syllabus Roadmap →Top 12 Senior Pandas & NumPy for Data Science Technical Interview Questions & Answers (2026)
Production-grade Pandas, NumPy, memory optimization, and vectorization technical interview questions with tested Python code answers for Data Science and Data Analytics hiring rounds:
Q1 What is the fundamental architectural difference between .loc and .iloc in Pandas?
.loc['a':'c'] are inclusive of both the start and stop labels. .iloc is strictly integer-position-based indexing: you specify rows and columns by their zero-based numerical positions (0 to length-1). Slices in .iloc[0:5] follow standard Python semantics and are exclusive of the stop index (indices 0 through 4 are returned). Passing non-integer keys to .iloc raises a TypeError.
Q2 Explain GroupBy.transform() vs GroupBy.apply() and how transform() prevents dimensional mismatch.
df['group_pct'] = df['sales'] / df.groupby('region')['sales'].transform('sum'). This avoids clunky merge operations and is 10x–50x faster.
Q3 How does Vectorization in NumPy/Pandas outperform Python for-loops, and what is SIMD execution?
Q4 How do you optimize memory usage on 10GB+ Pandas DataFrames without upgrading server RAM?
int64 and float64 consume 8 bytes per value. Using pd.to_numeric(downcast='integer') drops this to int16 (2 bytes) or int32 (4 bytes). 2) Convert low-cardinality object/string columns to 'category': Columns with repeated text values (e.g., states, departments, status codes) reduce from string pointers to a compact integer lookup table, saving 80%–90% RAM. 3) Use chunked processing: Process massive CSVs in streams using pd.read_csv('large.csv', chunksize=100000). 4) Use PyArrow engine: pd.read_csv('data.csv', engine='pyarrow', dtype_backend='pyarrow') for zero-copy Arrow memory structures.
Q5 Compare Merge vs Join vs Concat in Pandas: When should you use each?
how='inner'|'left'|'right'|'outer'|'cross'. DataFrame.join(): A convenient shorthand for merging two DataFrames primarily on their Index levels (or a column to an index). Default is a left join. pd.concat(): Binds multiple Series or DataFrames along an axis (axis=0 stacks rows vertically, axis=1 joins columns horizontally). Does not perform relational key matching; it aligns solely by index labels.
Q6 How does Pandas handle missing data (NaN vs None vs pd.NA) and how do you implement robust imputation?
np.nan (IEEE floating-point Not-a-Number) which forced integer columns to cast to float64. Python's None represents an object missing value. In modern Pandas (2.0+), pd.NA is the unified missing-data indicator backed by nullable extension types (Int64, boolean, string) which preserves integers without float casting. For production imputation: 1) Simple median/mode: df['age'].fillna(df['age'].median(), inplace=True), 2) Forward/backward fill for time series: df.bfill().ffill(), and 3) Group-specific imputation: df['salary'] = df.groupby('role')['salary'].transform(lambda x: x.fillna(x.median())).
Q7 What is Method Chaining in Pandas and how do .pipe() and .assign() write production-grade ETL code?
clean_df = (
raw_df.query('status == "ACTIVE"')
.assign(tax=lambda d: d['amount'] * 0.18,
total=lambda d: d['amount'] + d['tax'])
.pipe(remove_outliers, column='total')
.sort_values('total', ascending=False)
) Using .assign() with callable lambda expressions allows calculating derived columns on the fly during the chain, while .pipe() integrates custom domain functions cleanly.
Q8 How do Vectorized String Operations (.str accessor) compare to regex and lambda functions?
.str accessor executes string manipulation functions (.str.contains(), .str.extract(), .str.replace()) directly over array memory using vectorized compiled C routines. Using df['email'].apply(lambda x: re.search(r'@(.*)', x).group(1)) invokes the Python GIL and creates a Python object for every single row. In contrast, df['email'].str.extract(r'@(.*)', expand=False) is vectorized, executes 20x faster, and handles null values gracefully without throwing AttributeError on missing data.
Q9 Explain Time Series Resampling (resample vs rolling vs expanding) in Pandas.
df.resample('1H').agg({'price': 'ohlc'})), requiring a DatetimeIndex. .rolling(): Computes moving window metrics over a fixed window size (e.g. 30-day moving average: df['close'].rolling(window=30).mean()). .expanding(): Computes cumulative window metrics where the window starts at the beginning of the series and expands to include each subsequent row (e.g. cumulative year-to-date max or drawdown).
Q10 How do Window Functions with expanding and rolling handle min_periods and closed boundaries?
min_periods parameter specifies the minimum number of valid observations required in a window to produce a non-null result (e.g., df['val'].rolling(10, min_periods=3).mean() returns valid values once at least 3 numbers appear rather than returning 9 NaNs). The closed parameter ('right'|'left'|'both'|'neither') controls whether the window interval includes the endpoint, which is critical in quantitative finance to prevent lookahead bias where calculations accidentally leak future timestamp data into current decisions.
Q11 Compare Boolean Indexing vs DataFrame.query(): Performance, readability, and memory.
df[(df['age'] > 25) & (df['salary'] < 80000)] creates full boolean Series mask arrays in memory for each sub-clause before taking the logical AND. For large DataFrames (1M+ rows), df.query('age > 25 and salary < 80000') uses the NumExpr library backend which parses expressions into virtual machine bytecode, executes conditions in CPU cache blocks, avoids allocating large intermediate boolean masks, and offers significantly cleaner syntax for complex multi-column filters.
Q12 How do you manipulate MultiIndex columns and rows using unstack(), stack(), and pivot_table()?
index, columns, and values. .unstack(level): Pivots a row level of the index outward into a column level, widening the DataFrame. .stack(level): The inverse operation: pivots a column level inward into a row index, lengthening the DataFrame. To flatten a hierarchical MultiIndex column after aggregation into clean single strings: df.columns = ['_'.join(col).strip() for col in df.columns.values].
Q1 How does Pandas handle missing data (NaN vs None), and what is the difference between dropna() and fillna() methods?
Pandas uses NumPy NaN (float) to represent missing numerical data, while None is Python's native null object.
dropna() eliminates entire rows or columns along an axis according to threshold criteria, while fillna() replaces null values with mean, median, forward-fill (ffill), or backward-fill (bfill) methods to maintain dataset continuity.
Q2 What is the memory and performance difference between apply(), map(), and vectorized operations in Pandas?
Vectorized operations utilize precompiled C routines through NumPy ufuncs, executing orders of magnitude faster without Python interpreter overhead.
apply() iterates across rows or columns in Python bytecode, which is slow for large datasets. Vectorization should always be prioritized.
Q3 Explain the difference between loc and iloc in Pandas with multi-indexing.
loc is label-based selection where both start and stop boundaries are inclusive.
iloc is purely integer position-based (0 to length-1) where the stop boundary is exclusive, matching standard Python slicing.
Q4 How does Pandas groupby() work under the hood (Split-Apply-Combine)?
GroupBy partitions dataframe rows into subsets by hash values of the key columns, applies an aggregation or transformation function to each group in parallel, and combines the results into an output DataFrame.
Q5 What is broadcasting in NumPy and what are the strict rules for dimension compatibility?
Broadcasting allows NumPy to perform arithmetic operations on arrays of different shapes without unneeded memory copying.
Two dimensions are compatible when: 1. They are equal, or 2. One of them is 1. If lengths differ, dimensions are prepended with 1 on the left.
Q6 Explain memory optimization techniques for massive Pandas DataFrames (downcasting & categoricals).
Default float64 and int64 consume 8 bytes per value. Converting int64 to int16/int32 and object columns with low cardinality to 'category' dtypes often reduces memory usage by 80-90%.
Q7 How do you merge, join, and concatenate DataFrames in Pandas?
pd.concat() stacks dataframes along an axis (rows or columns) preserving indices.
pd.merge() performs database-style joins (inner, left, right, outer) based on common key columns, while DataFrame.join() merges on index values by default.
Q8 How do you detect and handle outliers in Pandas using IQR and Z-Score?
IQR method calculates Q1 (25th percentile) and Q3 (75th percentile). Any data point below Q1 - 1.5*IQR or above Q3 + 1.5*IQR is flagged as an anomaly.
Q9 What is method chaining and pipe() in Pandas and why is it preferred for production code?
Method chaining produces readable, functional transformations without creating unnecessary intermediate variables in memory.
Q10 How do you handle DateTime data in Pandas (resample, rolling window, timezones)?
Converting columns to pd.to_datetime enables powerful time-series operations such as resample('M') for monthly aggregates and rolling(window=7).mean() for moving averages.
Accelerate Your Career with Guaranteed Paid Internship*
Transparent ₹1,20,000 Fee (Inclusive of GST) • ₹10,000/month No-Cost EMI • 6-Month Corporate Paid Internship (₹15,000 – ₹35,000/mo stipend) with official IBM & Microsoft Credly credentials.
