python - 在 Pandas Python 中处理多重索引

标签 python pandas dataframe multi-index

考虑以下方式的数据,其中 ProductId 和 Date 是索引。我使用了以下代码

>>> df = df.set_index('Date').groupby('productID').resample('W').sum()

                   Sales
productID   Date    
1000    01/01/2017  10
        01/08/2017  15
        01/15/2017  64
        01/22/2017  21
        01/29/2017  21
1001    01/01/2017  15
        01/08/2017  54
        01/15/2017  51
        01/22/2017  19
        01/29/2017  56

我想通过以下方式调整结果

                                 Sales              
productID   01/01/2017  01/08/2017  01/15/2017  01/22/2017  01/29/2017
1000           10          15         64           21         21
1001           15          54         51           19         56

我正在尝试使用 Pandas 中的数据透视函数来做到这一点

df = df.pivot(index='ProductID', columns='Date', values='Sales')

但它返回以下错误

ValueError: cannot insert ProductID, already exists

请指导我如何以给定的方式转换结果。谢谢

最佳答案

我认为您需要添加 ['Sales'] 才能将 unstack 转换为 Series :

df = df.set_index('Date').groupby('productID').resample('W')['Sales'].sum().unstack(1)
#same as
#df = df.set_index('Date').groupby('productID').resample('W').sum()['Sales'].unstack(1)


print (df)
Date       01/01/2017  01/08/2017  01/15/2017  01/22/2017  01/29/2017
productID                                                            
1000               10          15          64          21          21
1001               15          54          51          19          56

关于python - 在 Pandas Python 中处理多重索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43325354/

相关文章:

python - 在 CSV 中搜索匹配字段并使用初始日期

python - 使用 PyUSB 通过 USB 发送数据

python - 如何在 zeep 中使用 wsdl 的每种方法发送 header ?

python - 使用 Pandas 将值与日期数据类型分开

python - 使用索引在 Pandas 中查找两个系列之间的交集

python - Pandas :当字典中有多个键时,通过映射添加列

python - 如何在 Pandas 数据框中用不同颜色为 bool 值着色

python - 将 2 列合并为 1 列

python - 如何使用networkx绘制子图

python - 如何计算 pandas DataFrame 中的 nan 值?