【问题标题】:How to group by values but keep data structure?如何按值分组但保持数据结构?
【发布时间】: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


【解决方案1】:

我们来玩吧:

import pandas as pd

df = pd.read_table('c:/4/AAA.txt', sep=',')
df.head(10)

df.groupby(['Week','Sales']).sum().sort_values('Sales')
df[(df['Sales']>30000)&(df['Year']==2019)].sort_values('Sales')
df[df['System_Type']=='Component2'].groupby('Sales').filter(lambda x: len(x)<2500).groupby('Sales').size().to_frame('size').sort_values('size')

【讨论】:

    猜你喜欢
    • 2022-12-06
    • 2021-03-25
    • 2012-05-03
    • 2017-02-15
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    相关资源
    最近更新 更多