stack / unstack
中等
22-pandas-only pandas 专属
stackunstackmultiindexreshape
sales_wide 是一张宽表:每行是一个 (region, product),四个季度的销售额分别放在 q1–q4 四列。
请把它转成“按产品和季度看各区域”的形状:
- 结果的 index 是两级 MultiIndex,层级名依次为
product、quarter;quarter 的取值就是原来的列名 q1、q2、q3、q4。
- 列为三个区域
north、south、east,值为对应的销售额。
- 每个出现过的产品,四个季度都要各输出一行,即使这一行全为 null。
- 原表里为 null 的单元格保持 null;某个区域没有这个产品的行时,对应的值也是 null。
输入
sales_wide(region, product, q1, q2, q3, q4),(region, product) 唯一;所有 case 的区域都只有 north、south、east。
输出
index 为 [product, quarter],列为 north, south, east。行顺序和列顺序不限。
输入表 (case base,共 2 个 case:base、gaps)
期望输出 (case base,行顺序不限)
| # | productString | quarterString | northFloat64 | southFloat64 | eastFloat64 |
| 1 |
coffee |
q1 |
200.0 |
250.0 |
180.0 |
| 2 |
coffee |
q2 |
210.0 |
240.0 |
185.0 |
| 3 |
coffee |
q3 |
190.0 |
260.0 |
200.0 |
| 4 |
coffee |
q4 |
220.0 |
275.5 |
210.0 |
| 5 |
juice |
q1 |
80.0 |
60.0 |
75.0 |
| 6 |
juice |
q2 |
95.0 |
65.0 |
88.0 |
| 7 |
juice |
q3 |
110.0 |
72.0 |
93.0 |
| 8 |
juice |
q4 |
70.0 |
58.0 |
81.0 |
| 9 |
tea |
q1 |
120.0 |
90.0 |
130.0 |
| 10 |
tea |
q2 |
135.5 |
100.0 |
128.0 |
| 11 |
tea |
q3 |
150.0 |
105.0 |
140.0 |
| 12 |
tea |
q4 |
160.0 |
98.0 |
155.0 |
共 12 行
参考答案 · stack / unstack