Pandas - 堆叠多重索引头但排除第一列
我有一个CSV文件,我用多重索引的表头把它读进了一个panda的数据框。下面是一个例子:
df = pd.DataFrame([[1,5,5,2,3], [2,10,4,20,3]])
df.columns = pd.MultiIndex.from_tuples((("1/1/2024","Store"), ("product code 1", "quantity onhand"), ("product code 1",'quantity sold'), ("product code 2", "quantity onhand"), ("product code 2",'quantity sold')))
df
2024年1月1日 商店 |
产品代码1 库存数量 |
产品代码1 销售数量 |
产品代码2 库存数量 |
产品代码2 销售数量 |
---|---|---|---|---|
1 | 5 | 5 | 2 | 3 |
2 | 10 | 4 | 20 | 3 |
第一列的日期是不需要的。我尝试过堆叠,但我需要保持商店的格式不变。能不能用透视表来得到下面这样的结果呢?
data = [[1,'product code 1',5,5],[1,'product code 2',3,2],[2,'product code 1',4,10],[2,'product code 2',3,20]]
columns = ['Store','Code','quantity sold','quantity onhand']
df2 = pd.DataFrame(data, columns=columns)
df2
商店 | 代码 | 销售数量 | 库存数量 |
---|---|---|---|
1 | 产品代码1 | 5 | 5 |
1 | 产品代码2 | 3 | 2 |
2 | 产品代码1 | 4 | 10 |
2 | 产品代码2 | 3 | 20 |
1 个回答
2
你可以暂时把第一列设置为索引,然后使用stack
这个功能:
(df.set_index(df.columns[0])
.stack(0)
.rename_axis(['Store', 'Code'])
.reset_index()
)
输出结果:
Store Code quantity onhand quantity sold
0 1 product code 1 5 5
1 1 product code 2 2 3
2 2 product code 1 10 4
3 2 product code 2 20 3