Consider the following DataFrame 'df':
Item Color Price(Rs) Units_in_stock 0 Pen Red 10 50 1 Pen Red 25 10 2 Pencil Black 7 47 3 Pencil Black 5 34 4 Pen Blue 50 55 5 Pen Blue 20 14
pivot3=df.pivot(index='Item', columns='Color ', values='Units_in_stock')
What will be the output of the above statement?
Consider the following DataFrame 'df':
| Item | Color | Price(Rs) | Units_in_stock | |
|---|---|---|---|---|
| 0 | Pen | Red | 10 | 50 |
| 1 | Pen | Red | 25 | 10 |
| 2 | Pencil | Black | 7 | 47 |
| 3 | Pencil | Black | 5 | 34 |
| 4 | Pen | Blue | 50 | 55 |
| 5 | Pen | Blue | 20 | 14 |
pivot3=df.pivot(index='Item', columns='Color ', values='Units_in_stock')
What will be the output of the above statement?
Solution
✅ Correct Option: 1
pivot() reshapes data without aggregating, so every (index, columns) pair must be unique. Here the pairs repeat:
| Item, Color | Rows |
|---|---|
| Pen, Red | 0 and 1 |
| Pencil, Black | 2 and 3 |
| Pen, Blue | 4 and 5 |
Pandas cannot decide which value of Units_in_stock to place in each cell, so it raises ValueError: Index contains duplicate entries, cannot reshape.
The space in 'Color ' is treated as a typo for 'Color'.
Use pivot_table() with an aggfunc such as sum or mean when duplicates exist.
Option 2: this output would appear only if each Item-Color pair occurred once.
Related questions:
2026: 21 May Shift 1
2026: 29 May Shift 2