pivot() takes three column references: index becomes the new row labels, columns' unique values become the new column headers, and values fills in the actual data at each resulting position. It requires each index/columns combination to appear at most once in the original data — if the same combination appears more than once, pivot() raises an error, since it has no way to decide which of the duplicate values should occupy that single cell, which is exactly the situation pivot_table() is designed to handle instead, by aggregating duplicates together.
1Understanding df.pivot()
pivot() takes three column references: index becomes the new row labels, columns' unique values become the new column headers, and values fills in the actual data at each resulting position. It requires each index/columns combination to appear at most once in the original data — if the same combination appears more than once, pivot() raises an error, since it has no way to decide which of the duplicate values should occupy that single cell, which is exactly the situation pivot_table() is designed to handle instead, by aggregating duplicates together.
If df.pivot() raises a 'duplicate entries' error, it means your index/columns combination isn't actually unique in the source data — use pd.pivot_table() instead, which aggregates duplicate combinations together, with a function like mean or sum, rather than requiring uniqueness.
import pandas as pd
df = pd.DataFrame({"date": ["2026-01-01", "2026-01-01", "2026-01-02"], "city": ["NYC", "LA", "NYC"], "temp": [30, 60, 32]})
print(df.pivot(index="date", columns="city", values="temp"))2Practical Example
Here is a real-world application of df.pivot() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"date": ["d1", "d1", "d1"], "city": ["NYC", "NYC", "LA"], "temp": [30, 31, 60]})
df.pivot(index="date", columns="city", values="temp")3Best Practices
Follow these guidelines when working with df.pivot():
1. Use pivot() specifically when you're confident each index/columns combination is already unique in your data
2. Reach for pd.pivot_table() instead of pivot() as soon as duplicate combinations are a realistic possibility, since it aggregates rather than erroring
3. Verify the resulting wide-format shape makes sense, expected row and column counts, after a pivot, as a quick sanity check
Tip: If df.pivot() raises a 'duplicate entries' error, it means your index/columns combination isn't actually unique in the source data — use pd.pivot_table() instead, which aggregates duplicate combinations together, with a function like mean or sum, rather than requiring uniqueness.
import pandas as pd
df = pd.DataFrame({"date": ["2026-01-01", "2026-01-01", "2026-01-02"], "city": ["NYC", "LA", "NYC"], "temp": [30, 60, 32]})
print(df.pivot(index="date", columns="city", values="temp"))