Online Python tutoring
Home

Pandas Interview Questions and Answers: 40 Questions for Python Interviews

Preparing for a Python, data analyst, business analyst or data science interview? These Pandas interview questions cover the operations employers commonly expect candidates to understand: Series and DataFrames, selecting and filtering data, missing values, grouping, combining tables, data cleaning and efficient analysis.

Each answer includes a concise explanation and, where useful, a Python example. Start with the fundamentals, then practise the scenario-based questions. Interviewers often care not only whether you know a method, but whether you can explain its output, limitations and appropriate use.

If you are new to Pandas, work through the complete Pandas tutorial first. You can also practise with our Pandas exercises with solutions, or review DataFrames, groupby() and merge().

Build practical Python skills

Need help preparing for a Python, data analyst or data science interview? Structured one-to-one tutoring can help you practise coding questions and explain your solutions clearly.

Get 1-on-1 Python Tutoring

1. Pandas fundamentals

1. What is Pandas in Python?

Pandas is a Python library for working with labelled, tabular and time-series data. It provides data structures such as Series and DataFrame, plus tools to import, clean, transform, summarise and analyse datasets.

2. What is the difference between a Series and a DataFrame?

A Series is a one-dimensional labelled array. A DataFrame is a two-dimensional table with row and column labels; its columns can hold different data types.

Python
import pandas as pd
s = pd.Series([10, 20, 30], name="score")
df = pd.DataFrame({"name": ["Aisha", "Bilal"], "score": [10, 20]})

3. How do you create a DataFrame?

Pass a dictionary of lists, a list of dictionaries, or another supported data structure to pd.DataFrame().

Python
df = pd.DataFrame({
    "Product": ["Pen", "Book", "Bag"],
    "Price": [2.5, 8.0, 25.0]
})

4. How do you inspect a DataFrame quickly?

Use head(), tail(), shape, columns, dtypes, info() and describe(). Together they help you understand its size, column types, missingness and numeric distributions.

Python
df.head()
df.shape
df.info()
df.describe(include="all")

5. How do you read a CSV file into Pandas?

Use pd.read_csv(). Common parameters include sep, usecols, dtype, parse_dates, na_values and encoding.

Python
df = pd.read_csv("sales.csv", usecols=["date", "region", "sales"])

6. How do you export a DataFrame to CSV without the index?

Python
df.to_csv("clean_sales.csv", index=False)

index=False prevents Pandas from writing the row index as an extra column.

2. Selecting, filtering and sorting data

7. What is the difference between loc and iloc?

loc selects by row and column labels; iloc selects by integer positions. Label-based slices with loc include the ending label, while positional slices with iloc exclude the ending position.

Python
df.loc[0, "sales"]
df.iloc[0, 2]
df.loc[0:3, ["region", "sales"]]
df.iloc[0:3, 1:3]

8. How do you select a single column and multiple columns?

Use df["sales"] for a Series, and df[["region", "sales"]] for a DataFrame containing two columns.

9. How do you filter rows using multiple conditions?

Use parenthesised Boolean conditions with element-wise operators: & for AND, | for OR and ~ for NOT.

Python
filtered = df[(df["sales"] > 1000) & (df["region"] == "North")]

Do not replace these operators with Python's and or or when comparing whole Series.

10. How do you sort a DataFrame?

Use sort_values() for column values and sort_index() for index labels.

Python
df.sort_values("sales", ascending=False)
df.sort_values(["region", "sales"], ascending=[True, False])

11. How do you select the top N records?

For the largest or smallest values in a column, use nlargest() or nsmallest(). They can be more direct than sorting the entire DataFrame and selecting its head.

Python
df.nlargest(5, "sales")
df.nsmallest(3, "sales")

12. How can you create a new column based on existing columns?

Python
df["revenue_after_tax"] = df["revenue"] * (1 - df["tax_rate"])

Prefer vectorised column expressions where possible instead of looping over individual rows.

3. Data cleaning and missing values

13. How do you identify missing values?

Use isna() or isnull(); these are equivalent aliases in common Pandas usage. Combine with sum() to count missing values per column.

Python
df.isna().sum()
df["sales"].isna()

14. What is the difference between dropna() and fillna()?

dropna() removes rows or columns according to missing-value rules. fillna() replaces missing entries with a chosen value or strategy. The appropriate choice depends on why values are missing and how much data would be lost.

Python
df.dropna(subset=["sales"])
df["sales"] = df["sales"].fillna(df["sales"].median())

15. How do you remove duplicate rows?

Use duplicated() to identify duplicates and drop_duplicates() to remove them. Use subset to define which columns determine duplication and keep to choose which occurrence remains.

Python
df.duplicated().sum()
df.drop_duplicates(subset=["customer_id"], keep="last")

16. How do you rename columns?

Python
df = df.rename(columns={"Sales Amount": "sales_amount"})

rename() changes specified labels; assigning a complete list to df.columns replaces all column labels and requires the correct number of names.

17. How do you convert a column to a different data type?

Use astype() for straightforward conversions and pd.to_numeric() or pd.to_datetime() when parsing strings into numeric or date values.

Python
df["quantity"] = pd.to_numeric(df["quantity"], errors="coerce")
df["date"] = pd.to_datetime(df["date"], errors="coerce")

18. What is the difference between map(), replace() and apply()?

map() is often used to map values in a Series using a dictionary or function. replace() substitutes specified values or patterns. apply() applies a function along a Series or DataFrame axis. For simple arithmetic, vectorised operations are often clearer and faster.

4. Grouping and aggregation

19. What does groupby() do?

groupby() splits records into groups, applies a calculation and combines the results. It is useful for summaries such as sales by region or average salary by department.

Python
df.groupby("region")["sales"].sum()
df.groupby("region").agg(total_sales=("sales", "sum"), average_sales=("sales", "mean"))

20. What is the difference between count(), size() and nunique()?

count() counts non-missing values in each selected column; size() counts rows in each group, including rows where a particular column is missing; nunique() counts distinct values, excluding missing values by default.

21. What is the difference between agg() and transform()?

agg() typically returns a summary with fewer rows, such as one row per group. transform() returns results aligned to the original rows, which is useful for adding group-level statistics to each record.

Python
df["region_average"] = df.groupby("region")["sales"].transform("mean")

22. How do you calculate a running total?

Python
df = df.sort_values("date")
df["running_sales"] = df["sales"].cumsum()

For a separate running total per group, sort by the relevant time/order column and use groupby(...)[column].cumsum().

5. Merging and concatenating DataFrames

23. What is the difference between merge() and concat()?

merge() joins tables using matching key columns or indexes, much like a database join. concat() stacks objects along an axis, usually adding rows or columns, and aligns labels along the other axis.

24. What are inner, left, right and outer joins?

An inner join keeps keys present in both tables. A left join keeps every left-table key, a right join keeps every right-table key, and an outer join keeps keys from both tables. Unmatched columns are generally filled with missing values.

Python
result = customers.merge(orders, on="customer_id", how="left")

25. Why can a merge unexpectedly increase the number of rows?

If a join key appears multiple times on either side, one key can match several records. Check key uniqueness and use the validate argument where appropriate.

Python
result = left.merge(right, on="customer_id", validate="one_to_one")

26. How do you combine DataFrames row by row?

Python
combined = pd.concat([jan_sales, feb_sales], ignore_index=True)

Column labels are aligned. If one DataFrame has a column missing from another, the resulting column contains missing values for those rows.

27. How do you find records in one table that have no match in another?

Use a left merge with indicator=True, then filter rows labelled left_only.

Python
checked = left.merge(right, on="id", how="left", indicator=True)
unmatched = checked[checked["_merge"] == "left_only"]

6. Advanced and performance questions

28. Why are vectorised operations generally preferred to row loops?

Vectorised operations use optimised array operations and usually express intent more clearly. They are often faster than Python-level loops or row-wise apply(axis=1), although performance depends on the operation and data.

29. How do you reduce memory use for a large DataFrame?

Read only necessary columns, choose appropriate numeric types, use categorical types for suitable repeated text values, inspect memory with memory_usage(deep=True), and process very large files in chunks when appropriate.

Python
df.memory_usage(deep=True).sum()
small = pd.read_csv("large.csv", usecols=["date", "sales"], chunksize=100_000)

30. How do you process a CSV that is too large to fit comfortably in memory?

Use chunksize with read_csv() to process batches, aggregate each batch, and combine the partial results. Chunking helps only when the workflow can be organised around batch processing.

31. What is chained indexing, and why should it be avoided?

Chained indexing performs selection in multiple steps, such as df[df["sales"] > 0]["flag"] = True. It can lead to ambiguous assignment behaviour. Prefer a single .loc assignment.

Python
df.loc[df["sales"] > 0, "flag"] = True

32. What is the difference between sort_values() and sort_index()?

sort_values() orders records by one or more column values. sort_index() orders records by their row or column labels.

33. How can you work safely with dates?

Parse date strings using pd.to_datetime(), inspect invalid values, and use the .dt accessor for date components. Make sure date formats and time zones are handled consistently.

Python
df["date"] = pd.to_datetime(df["date"], errors="coerce")
df["month"] = df["date"].dt.month

34. How do you find distinct values in a column?

Python
df["region"].unique()
df["region"].nunique()
df["region"].value_counts(dropna=False)

unique() returns the distinct values, nunique() counts them, and value_counts() counts the frequency of each value.

7. Scenario-based Pandas interview questions

35. A sales column was imported as text. How would you clean it?

Inspect representative values first, remove known formatting characters if appropriate, and convert with pd.to_numeric(). Use errors="coerce" only when invalid values should become missing values and will be inspected afterwards.

Python
df["sales"] = (df["sales"].astype("string")
    .str.replace(",", "", regex=False)
    .str.replace("$", "", regex=False))
df["sales"] = pd.to_numeric(df["sales"], errors="coerce")

36. You need total revenue by month. What steps would you take?

Convert the date column to datetime, confirm revenue is numeric, then group by a monthly period or resample a datetime index. Decide how to handle missing dates and values before reporting totals.

Python
df["date"] = pd.to_datetime(df["date"])
monthly = df.groupby(df["date"].dt.to_period("M"))["revenue"].sum()

37. Two tables contain customer details and orders. How would you combine them?

Identify the intended key, inspect whether it is unique in each table, choose a join type based on the question, and validate the resulting row count and unmatched records.

38. How would you investigate an unexpected increase in row count after merging?

Compare row counts before and after the merge, count duplicated keys on both sides, inspect key data types and whitespace, and use validate or indicator=True to check the relationship and unmatched rows.

39. How would you handle missing values before training a machine-learning model?

Measure missingness, investigate why values are absent, select an appropriate strategy for each feature, and fit imputation on training data only. Apply the fitted strategy to validation and test data to avoid leakage.

40. How would you make a Pandas analysis reproducible?

Use clear transformation steps, meaningful column names, explicit data types, documented assumptions, stable input files, and checks for row counts, duplicate keys and missing values. Keep cleaning and analysis steps easy to rerun.

Frequently asked questions

How many Pandas questions should I practise for an interview?

Start with the fundamentals and practise the scenario-based questions until you can explain both the code and the reasoning. The right number depends on the role and interview format.

Which Pandas topics are most important for data analyst interviews?

Prioritise DataFrame selection and filtering, missing values, sorting, grouping, aggregation, joining tables, data types and data cleaning. Be ready to explain how you validate results.

Should I memorise Pandas syntax?

Learn the core patterns, but focus on understanding the data operation and reading documentation. Interviewers may change the dataset or requirements, so reasoning is more valuable than memorising isolated snippets.

How can I practise these interview questions?

Run the examples in Jupyter Notebook or Google Colab, change the sample data, predict the output before running the code, and explain your solution aloud. Then try the Pandas exercises.

Continue learning Pandas

Interview preparation tip: For each answer, practise explaining the goal, the code, the expected result and one potential edge case.

Explore one-to-one Python tutoring if you would like structured help with Python and data analysis.



Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net