【发布时间】:2019-08-22 17:48:17
【问题描述】:
我有一个数据集,其中包含销售系统的单位(商店)列表,每周都有销售和单位。我已将它们分组为一个测试组和一个控制组,作为一个新列。
我现在想做的是在数据集中使用这些新组,因为我想在所有星期内将它们相互绘制。
到目前为止,我在这方面的最佳表现是:
df_group = df.groupby('Group')['Sales'].sum()
然而,这只是总结它们,而不是每周。
Unit Year Week System_Type Sales Units_Sold
0 6111 2019 1 Component2 109578 3139
1 6111 2019 1 Component1 20792 639
2 6111 2019 2 Component2 115363 3425
3 6111 2019 2 Component1 25261 796
4 6111 2019 3 Component2 114913 3352
df['Group'] = np.where(((df['Unit'] == 6111) | (df['Unit'] == 6112) | (df['Unit'] == 6121)), 'control', 'test')
df.head()
Unit Year Week System_Type Sales Units_Sold Group
0 6111 2019 1 Component2 109578 3139 control
1 6111 2019 1 Component1 20792 639 control
2 6111 2019 2 Component2 115363 3425 control
3 6111 2019 2 Component1 25261 796 control
4 6111 2019 3 Component2 114913 3352 control
time = df.Week.unique()
df_cat = df[df.System_Type == 'Component1']
我一直在研究这个问题,但无法通过谷歌搜索找到正确的解决方案。我在想也许可以使用“时间”变量作为新索引?
非常感谢任何帮助!
【问题讨论】:
-
如果你想分组和求和并保持相同的索引然后使用转换,如下所示:
df.groupby('Week')['Sales'].transform('sum') -
所以
df_group = df.groupby(['Week','Group')['Sales'].sum() -
@Wen-Ben 缺少
] -
谢谢,完美!
标签: python python-3.x pandas pandas-groupby