Skip to main content

A sales table has one row per store and month with a sales value. Turn it into a wide table with one row per store and one column per month. For example, rows S1 Jan 10 and S1 Feb 20 become one S1 row with Jan = 10 and Feb = 20.

Coding rounds · Intermediate 1

Short answer

Use pivot_table with an explicit aggregation: df.pivot_table(index="store", columns="month", values="sales", aggfunc="sum", fill_value=0). pivot is stricter and raises an error when a store and month pair repeats. Both are about O(n) after grouping; the wide table needs stores times months cells.

Deeper answer

First clarify the shape. Ask whether a store and month pair can appear more than once, and if so whether to sum or average. Ask what an absent pair should show: zero or missing. Ask how many distinct months there are, because each becomes a column.

If every pair is unique, df.pivot(index="store", columns="month", values="sales") is enough, and it raises a ValueError on duplicates, which is a useful check. If pairs can repeat, use df.pivot_table(index="store", columns="month", values="sales", aggfunc="sum", fill_value=0). Always name the aggfunc, because the default is the mean and that silently averages duplicates. Finish with reset_index() to make store a normal column again.

Memory is the number of stores times the number of months, so a column with many distinct values makes a very wide table. Month names sort by alphabet, so use a real date or an ordered category to get calendar order. Test a duplicate pair, a store with a month absent, and an empty table. Say that melt is the reverse step, from wide back to long.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Tables with pandas

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.