← Back to Pandas Course | Chapter 9: Reshaping Data | Lesson 3 of 6

pivot()

pivot reshapes long data into a wide table without any aggregation.

In this page:

  1. pivot()
Syntax
python
wide = df.pivot(index="row_column", columns="column_column", values="value_column")

pivot()

pivot(index, columns, values) makes unique index/column combinations into a grid. It raises an error if a combination appears twice; use pivot_table when duplicates need aggregation. Keyword arguments are required in recent versions.

Note: pivot is the inverse of melt for clean data.

Example: pivot()

python
import pandas as pd

long = pd.DataFrame({"name": ["Ann", "Ann", "Bob", "Bob"], "subject": ["math", "art", "math", "art"], "score": [90, 70, 80, 85]})
print(long.pivot(index="name", columns="subject", values="score"))

# Output:
# subject  art  math
# name
# Ann       70    90
# Bob       85    80
Related Topics
Common Mistakes
  1. Passing duplicate index/column pairs
  2. Using positional arguments in newer pandas
  3. Expecting aggregation
Chapter Summary
  • pivot reshapes without aggregating
  • Combinations must be unique
  • Use pivot_table for duplicates
  • Inverse of melt
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.