我正在尝试制作一个数据透视表,使其看起来像下面第一个表中的数据的预期结果(第二个表);
To Date From To Quantity
10/11/2020 USA Ireland 5
10/11/2020 USA France 4
11/11/2020 USA France 6
12/11/2020 USA Jamaica 6
12/11/2020 USA France 5
.
.
.
14/02/2021 USA Ireland 65
01/11/2020 01/12/2020 01/01/2021 01/02/2021
Ireland 15 65
France 10
Jamaica 6
我可以 groupby() 它来获取每月的数据.. 我希望数据透视表包含每个国家/地区的总金额..
df.index = qathist['To Date']
df.index = pd.to_datetime(df.index)
df_m= df.groupby(by=[df.index.year, df.index.month]).sum()
..但随后我删除了其他数据等,但似乎无法正确旋转它!
非常感谢任何帮助!!
最佳答案
要获取每月的数据,最好使用 to_period
。您可以通过To
进行groupby,然后unstack:
df.groupby(['To',df.index.to_period('M')])['Quantity'].sum().unstack()
关于python - 带 Groupby 的数据透视表 - Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64158772/