Skip to main contentSkip to solution

Consider the following DataFrame 'df':

ItemColorPrice(Rs)Units_in_stock
0PenRed1050
1PenRed2510
2PencilBlack747
3PencilBlack534
4PenBlue5055
5PenBlue2014

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, ColorRows
Pen, Red0 and 1
Pencil, Black2 and 3
Pen, Blue4 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.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question