将数据透视表分为三个级别

时间:2019-05-07 10:59:47

标签: python dataframe reshape

我在excel中有如下数据集-

enter image description here

我想按以下方式重塑数据-

enter image description here

尽管我可以使用pivot_table()函数,但不能创建三个级别的标题。同样,一旦使用数据透视表调整了数据的形状,便无法重命名列。 请提出必要的步骤(即逻辑或任何可用功能)。 预先感谢。

1 个答案:

答案 0 :(得分:1)

透视并将您的标识符列设置为索引,透视之后交换级别

# df be your original dataframe
df = df.pivot_table(index=["SYMBOL", "NAME"], columns=["date"], values=["price", "price2"])
df.swaplevel(0, 1, axis=1). sort_index(axis=1)