How can you pivot data in a DataFrame?

Quick Overview

A pandas interview question asking how to reshape a long DataFrame into a wide one with a pivot. It tests whether you know the roles of index, columns and values, when each pivot method applies, and how duplicate and missing combinations are handled.

How can you pivot data in a DataFrame?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

How can you pivot data in a DataFrame? Assume a pandas DataFrame in long format, for example one row per date and product with a sales value. ```hint Watch for repeated pairs Think about what should happen when two rows share the same row label and the same column label. ``` ### What a Strong Answer Covers - The three roles a pivot assigns: the row index, the new columns, and the cell values - The difference between `pivot()` and `pivot_table()`, and when each one applies - How duplicate pairs and missing combinations are handled (aggregation, NaN, fill values) - How to go back from wide to long format, and how to flatten the pivoted result for further use ### Follow-up Questions - `pivot()` raises "Index contains duplicate entries, cannot reshape". What does that tell you about the data, and how do you fix it? - How would you build a pivot that shows both the sum and the count of sales in each cell? - How would you do the same reshape in SQL? - How do `unstack()` and `pd.crosstab()` relate to `pivot_table()`?

Overview: A pandas interview question asking how to reshape a long DataFrame into a wide one with a pivot. It tests whether you know the roles of index, columns and values, when each pivot method applies, and how duplicate and missing combinations are handled.

General logo
General
Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

How can you pivot data in a DataFrame?

Assume a pandas DataFrame in long format, for example one row per date and product with a sales value.

What a Strong Answer Covers Guidance

  • The three roles a pivot assigns: the row index, the new columns, and the cell values
  • The difference between pivot() and pivot_table() , and when each one applies
  • How duplicate pairs and missing combinations are handled (aggregation, NaN, fill values)
  • How to go back from wide to long format, and how to flatten the pivoted result for further use

Follow-up Questions Guidance

  • pivot() raises "Index contains duplicate entries, cannot reshape". What does that tell you about the data, and how do you fix it?
  • How would you build a pivot that shows both the sum and the count of sales in each cell?
  • How would you do the same reshape in SQL?
  • How do unstack() and pd.crosstab() relate to pivot_table() ?