考虑以下方式的数据,其中 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/