Pandas按CodeProduct索引转置行:将分层列索引改为店铺_价格/库存格式
解决Pandas透视表分层列索引合并为店铺_指标格式的问题
问题场景
SQL查询返回数据集的主键为CodeProduct与ShopName的组合,包含1000行数据、20个不同店铺,数据结构如下:
| CodeProduct | ShopName | Price | Stock |
|---|---|---|---|
| 0001 | FruitsStore | 2,2 | 322 |
| 0001 | BigStore | 2,1 | 5666 |
| 0002 | FruitStore | 3,3 | 33333 |
| 0003 | HelloStore | 5,99 | 65 |
将数据导入Pandas DataFrame:
mytable = pd.read_sql(myrequest, db)
使用pivot_table转置店铺为列时,得到了分层列索引(上层为Price/Stock,下层为店铺名),但需要将列名合并为ShopName_Price、ShopName_Stock的扁平化格式,消除分层索引。
解决方法
执行透视表操作后,通过处理列名实现分层索引的合并:
# 执行透视表 mytable = pd.pivot_table( mytable, index='CodeProduct', columns='ShopName', values=['Price', 'Stock'], aggfunc='first', dropna=False ) # 合并分层列索引为"店铺名_指标名"格式 mytable.columns = ['_'.join(reversed(col)) for col in mytable.columns] # 可选:将CodeProduct从索引转为普通列 mytable = mytable.reset_index()
说明
- 透视表返回的分层列元组格式为
(指标名, 店铺名),通过reversed(col)反转顺序后,用下划线连接得到店铺名_指标名;若需要指标名_店铺名格式,直接使用'_'.join(col)即可。 - 处理后的数据列名会变为
BigStore_Price、BigStore_Stock、FruitsStore_Price等,完全符合需求。
内容的提问来源于stack exchange,提问作者Malou
相关产品推荐
相关产品推荐

