LearnFrenzy
Sign in Take a free test

Python Programming interview · Set 14 of 19

Python for Data and AI (NumPy, pandas)

  • 5 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Think in columns, not loops

Data interviews reward vectorised thinking and careful data cleaning. Show that you inspect data first, handle missing values deliberately and check your joins.

  • NumPyArrays, vectorisation and broadcasting.
  • pandasLoading, cleaning, groupby and merge.
  • ProjectsEnvironments, secrets and AI SDKs.

Python is the language of data and AI, so even backend and analyst roles now ask a few NumPy and pandas questions. Interviewers want to see vectorised thinking — working with whole columns instead of loops — and clean handling of messy data.

1. Why is NumPy faster than Python lists?

A NumPy array stores numbers of one type in a contiguous block of memory, and operations run in optimised C code over the whole array (vectorisation) instead of a Python loop per element. That is often 10–100× faster and uses far less memory.

import numpy as np

prices = np.array([120.0, 80.5, 99.9])
with_gst = prices * 1.18          # one vectorised operation, no loop
print(with_gst.round(2))

2. What is broadcasting in NumPy?

Broadcasting lets NumPy combine arrays of different shapes by stretching the smaller one along missing dimensions, without copying data — for example subtracting each column's mean from a matrix.

scores = np.array([[70, 80], [90, 60], [50, 100]])
centered = scores - scores.mean(axis=0)   # (3,2) minus (2,) → broadcast across rows

3. How do you load and explore a dataset with pandas?

Read it into a DataFrame and inspect shape, types, missing values and summary statistics before doing anything else.

import pandas as pd

df = pd.read_csv("orders.csv", parse_dates=["created_at"])
print(df.shape)
df.info()                    # column types and non-null counts
print(df.describe())         # numeric summary
print(df.isna().sum())       # missing values per column

4. How do you handle missing values?

First understand why they are missing. Then drop rows or columns (dropna) when few values are missing at random, fill with a sensible value (fillna with median, mode or a constant), or add an “is_missing” flag so a model can learn from the gap.

df["city"] = df["city"].fillna("Unknown")
df["amount"] = df["amount"].fillna(df["amount"].median())
df = df.dropna(subset=["customer_id"])

5. Explain groupby with an example.

groupby splits rows into groups, applies an aggregation to each, and combines the results — like SQL GROUP BY. Named aggregation keeps output columns readable.

summary = (df[df["status"] == "PAID"]
           .groupby("city")
           .agg(orders=("id", "count"), revenue=("amount", "sum"))
           .sort_values("revenue", ascending=False)
           .head(5))

6. How do you join two DataFrames?

Use merge, which works like SQL joins with how='inner' | 'left' | 'right' | 'outer'. Check row counts before and after — an unexpected increase usually means duplicate keys.

orders = orders.merge(customers[["id", "segment"]], left_on="customer_id", right_on="id",
                      how="left", validate="many_to_one")   # raises if customers has duplicate ids

7. Why should you avoid apply() and loops over rows?

Row-wise loops and apply run Python code per row and are slow on large data. Prefer vectorised column operations, np.where, map with a dict, or built-in string methods via .str.

# slow
df["tier"] = df.apply(lambda r: "high" if r["amount"] > 5000 else "low", axis=1)
# fast
df["tier"] = np.where(df["amount"] > 5000, "high", "low")

8. How do you set up a clean Python project for an AI app?

Create an isolated environment (venv or uv), pin dependencies in pyproject.toml with a lock file, keep API keys in environment variables (never in code), and add type hints, tests and a formatter such as Ruff. Use the official SDK of the AI provider rather than raw HTTP calls.

uv init support-bot && cd support-bot
uv add anthropic pandas
export ANTHROPIC_API_KEY="..."     # from your secrets manager, never committed
uv run python main.py

Remember

Key points

  • Vectorise

    Column operations beat row loops.

  • Inspect first

    shape, info, describe, isna before analysis.

  • Validate merges

    Use validate= and compare row counts.

  • Secrets in env vars

    Never hard-code API keys.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What is the difference between loc and iloc? Basic

    loc selects by labels (index names, column names); iloc by integer positions.

  2. 2 How do you remove duplicate rows? Basic

    df.drop_duplicates(subset=[...], keep="first").

  3. 3 How do you read a CSV that does not fit in memory? Intermediate

    Read in chunks with chunksize, select only needed columns with usecols, set compact dtypes, or use Polars or DuckDB.

  4. 4 What is the difference between a pandas Series and a DataFrame? Basic

    A Series is one labelled column; a DataFrame is a table of Series sharing an index.

  5. 5 How do you make an analysis reproducible? Intermediate

    Pin dependency versions, fix random seeds, keep raw data unchanged, script every step (no manual edits) and track notebooks or pipelines in version control.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links