Pandas 表-扩展到行的索引值

Pandas 表-扩展到行的索引值,pandas,indexing,pivot-table,Pandas,Indexing,Pivot Table,我试图整理一些数据,特别是通过选取两列“measure”和“value”,并为度量值的每个唯一值创建更多的列 到目前为止,我已经有了一些python(3)代码,可以读入数据并将其旋转到我想要的形式——大致上。此代码如下所示: import pandas as pd #Load the data df = pd.read_csv(r"C:\Users\User\Documents\example data.csv") #Pivot the dataframe df_pivot = df.pivo

我试图整理一些数据,特别是通过选取两列“measure”和“value”,并为度量值的每个唯一值创建更多的列

到目前为止,我已经有了一些python(3)代码,可以读入数据并将其旋转到我想要的形式——大致上。此代码如下所示:

import pandas as pd
#Load the data
df = pd.read_csv(r"C:\Users\User\Documents\example data.csv")

#Pivot the dataframe
df_pivot = df.pivot_table(index=['Geography Type', 'Geography Name', 'Week Ending',
 'Item Name'], columns='Measure', values='Value')

print(df_pivot.head())
这将产生:

Measure                                               X   Y   Z
Geography Type Geography Name Week Ending Item Name            
Type 1         Total US       1/1/2018    Item A     57  51  16
                                          Item B     95  37  17
                              1/8/2018    Item A     92   8  32
                                          Item B     36  49  54
Type 2         Region 1       1/1/2018    Item A     78  46  88
这几乎是完美的,但对于我的工作,我需要将此文件放入软件中,为了让软件正确读取数据,它需要每个行的值,因此我需要每个索引的列值通过行进行扩展,如下所示:

Measure                                               X   Y   Z
Geography Type Geography Name Week Ending Item Name            
Type 1         Total US       1/1/2018    Item A     57  51  16
Type 1         Total US       1/1/2018    Item B     95  37  17
Type 1         Total US       1/8/2018    Item A     92   8  32
Type 1         Total US       1/8/2018    Item B     36  49  54
Type 2         Region 1       1/1/2018    Item A     78  46  88

诸如此类。

它已经做到了,你只是这样看,因为熊猫是如何展示它的。运行
df.reset_index()
你就会看到。啊,明白了。我在我的初始代码中有这个,但一定是以某种方式覆盖了它,我想在这样做之后没有将它指定为新对象?无论如何,使用此方法并将其分配给df_new修复了所有问题,包括输出文件的格式。非常感谢。