Skip to content
Programs · Program 3-11

Q.Write the statement to print the maximum price of pen of each color.

Puducherry TnboardTextbookSubjective· 2mImportance★★★★★
34% · 18/53 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Filter the stock DataFrame to just the Pen rows, then build a pivot_table() with Color as the new columns and max (not the default mean) as the aggregate function over Price(Rs), collapsing each color's two duplicate prices down to the higher one.

Recap: what pivot_table() needs

pandas.pivot_table(data, values=None, index=None, columns=None, aggfunc='mean')

index sets the row labels, columns sets the new column labels, values picks which column(s) get aggregated, and aggfunc decides how duplicate entries are combined — its default is mean. Earlier in this same section, the unfiltered stock data (Item/Color/Price(Rs)/Units_in_stock, 6 rows: 2 Red pens, 2 black pencils, 2 blue pens) was pivoted with the default mean — e.g. the blue pen's two prices, 50 and 20, averaged to 35.0. Here we deliberately override that default with aggfunc=[max] to get the highest price instead of the average.

Step 1 — filter to Pen rows only

dfpen = df[df.Item == 'Pen']
print(dfpen)

Output:

   Item Color  Price(Rs)  Units_in_stock
0   Pen   Red         10              50
1   Pen   Red         25              10
4   Pen  Blue         50              55
5   Pen  Blue         20              14

Filtering first is safe here because the stock data never has a Pen colored Black (Black only ever appears for Pencil) — so restricting to Item == 'Pen' cleanly leaves just the Red and Blue rows, with no color accidentally dropped from the result.

Step 2 — pivot with max as the aggregate function

pivot_redpen = dfpen.pivot_table(index='Item', columns=['Color'], values=['Price(Rs)'], aggfunc=[max])
print(pivot_redpen)

Output:

             max
         Price(Rs)
Color    Blue  Red
Item
Pen        50   25

Color's two values (Red, Blue) become the new columns; the duplicate prices within each color (Red: 10 and 25; Blue: 50 and 20) collapse to their maximum (25 and 50 respectively) instead of averaging.

Reading the multi-level column header …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.