📊 2026 Career Guide
⚡ 2026 Verified Program Offer: 6 Months 100% Live Training • ₹1,20,000 Flat Fee (₹10,000/mo 0% EMI) • Official IBM & Microsoft Badges • Guaranteed 6-Mo Paid Internship*
📥 Download 2026 Syllabus & Fee PDF →
FREE 2026 PDF DOWNLOAD • VERIFIED LAB CODE

📥 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 is label-based indexing: you specify rows and columns by their index and column labels (strings, dates, boolean series). The key operational distinction is that slice bounds in .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.

GroupBy.apply() is a flexible aggregation or split-apply-combine operation that passes each sub-dataframe group to a custom Python function. It can return a scalar, Series, or DataFrame of arbitrary dimension, which Pandas attempts to reassemble. GroupBy.transform() requires the function to return a result that has the exact same number of rows as the input group. It broadcasts the calculated metric (such as group mean, z-score, or percent of total) directly back to the original DataFrame's index without altering its shape: 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?

Python for-loops operate via dynamic interpretation: on every iteration, Python checks variable types, handles reference counting, and looks up methods. In contrast, Vectorization delegates batch mathematical operations to compiled, contiguous C/Fortran memory buffers. NumPy arrays use single-type homogeneous blocks in contiguous RAM, enabling CPU hardware to utilize SIMD (Single Instruction, Multiple Data) vector registers (AVX-512, SSE). A single CPU clock cycle executes calculations across 4 to 16 data points simultaneously, achieving 100x–300x speedups over pure Python loops.

Q4 How do you optimize memory usage on 10GB+ Pandas DataFrames without upgrading server RAM?

Memory optimization follows four production techniques: 1) Downcast numeric types: Default 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?

pd.merge(): The most comprehensive relational algebra join tool (equivalent to SQL JOIN). Joins two DataFrames on one or more arbitrary columns or indices using 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?

Historically, Pandas used NumPy's 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?

Method chaining combines multiple transformation steps into a single readable, immutable pipeline without creating throwaway intermediate variables:
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?

The .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.

.resample(): Frequency-based grouping (similar to GroupBy for dates/times). It converts time series between granularities (e.g. from 1-minute ticks to 1-hour candles: 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?

The 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.

Boolean indexing: 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()?

A MultiIndex represents hierarchical index dimensions. pivot_table(): Aggregates raw transactional data into a spreadsheet-style pivot format specifying 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.

PYTHON EXAMPLE
import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [1, np.nan, 3], 'B': [np.nan, 5, 6]})
df['A_filled'] = df['A'].fillna(df['A'].median())
clean_df = df.dropna(subset=['B'])

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.

PYTHON EXAMPLE
# Vectorized (Fastest O(N))
df['total'] = df['price'] * df['quantity']

# apply() with lambda (10-50x slower)
df['total'] = df.apply(lambda row: row['price'] * row['quantity'], axis=1)

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.

PYTHON EXAMPLE
df.loc[df['salary'] > 80000, ['emp_name', 'department']]
df.iloc[0:10, 0:3] # First 10 rows, first 3 columns

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.

PYTHON EXAMPLE
df.groupby('department').agg({'salary': ['mean', 'max'], 'experience': 'median'})

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.

PYTHON EXAMPLE
a = np.array([1, 2, 3]) # shape (3,)
b = np.array([[10], [20], [30]]) # shape (3, 1)
result = a + b # shape (3, 3)

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%.

PYTHON EXAMPLE
df['category_col'] = df['category_col'].astype('category')
df['id_col'] = pd.to_numeric(df['id_col'], downcast='integer')

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.

PYTHON EXAMPLE
merged = pd.merge(orders, customers, on='customer_id', how='left')

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.

PYTHON EXAMPLE
Q1 = df['revenue'].quantile(0.25)
Q3 = df['revenue'].quantile(0.75)
IQR = Q3 - Q1
clean = df[(df['revenue'] >= Q1 - 1.5*IQR) & (df['revenue'] <= Q3 + 1.5*IQR)]

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.

PYTHON EXAMPLE
def clean_data(df):
    return (df
            .dropna(subset=['email'])
            .assign(name=lambda d: d['name'].str.strip().str.title())
            .query('age >= 18'))

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.

PYTHON EXAMPLE
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
weekly_avg = df['sales'].rolling(window=7).mean()
2026 Career Fast-Track

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.