pivot()
pivot reshapes long data into a wide table without any aggregation.
In this page:
Syntax
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()
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
- Passing duplicate index/column pairs
- Using positional arguments in newer pandas
- 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: