Stack Two Quarterly DataFrames With Quarter Labels in a MultiIndex
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `concat_with_source(q1, q2)` that stacks two quarterly DataFrames vertically, tagging each block with its source quarter. Both inputs have columns `['product', 'sales']`. Return the resulting DataFrame.
Requirements:
- Use `pd.concat`, labeling the blocks `'Q1'` and `'Q2'` in the index. Do not reset or ignore the original row index.
- Keep columns `['product', 'sales']` unchanged.
- Return a 2-level MultiIndex: level 0 is the quarter key (`'Q1'`/`'Q2'`), level 1 is the original row index.
- All `Q1` rows first, then all `Q2` rows.
Example:
```python
q1 = pd.DataFrame({'product': ['A', 'B'], 'sales': [10, 20]})
q2 = pd.DataFrame({'product': ['A', 'C'], 'sales': [15, 5]})
concat_with_source(q1, q2)
# product sales
# Q1 0 A 10
# 1 B 20
# Q2 0 A 15
# 1 C 5
```
```hint Labeling the blocks
Look through the arguments `pd.concat` accepts for naming each input block, and check which option would throw the row index away.
```
### Constraints & Assumptions
- Both inputs have exactly the columns `['product', 'sales']`.
- Each input keeps whatever index it arrives with, and the two frames can share index labels (both start at `0` in the example).
### What a Strong Answer Covers
- How each block gets its quarter label, and how the labels are matched to the input frames.
- Why the original row index has to survive, and which option would discard it.
- The shape of the resulting index and the order of the rows.
- How to read one quarter back out of the combined frame.
### Follow-up Questions
- How would you flatten the MultiIndex into a regular `quarter` column?
- What changes if `q1` and `q2` have different columns?
- How would you extend this to a dictionary of many quarters, with named index levels?
Overview: Write a pandas function that stacks two quarterly sales DataFrames and labels each block with its quarter in a two-level MultiIndex. It tests pd.concat options, keeping the original row index, reading blocks back by label and flattening the index into a column.