【问题标题】:Calculate subtotals in Pandas sorted by level计算按级别排序的 Pandas 小计
【发布时间】:2022-01-06 20:00:22
【问题描述】:

我想计算这个数据集的小计:

Country  Channel    Genre  Size   Prev
UK       Partners   Blues    25     20
UK       Stores     Blues    15     10
UK       Stores     Rock     35     30
US       Stores     Rock     45     40
UK       Partners   Rock     55     50
US       Partners   Rock     65     60
UK       Stores     Blues     5      2

This solution 计算小计,但我需要对每个级别进行不同的排序。具体来说:

>>> columns = ['Country', 'Channel', 'Genre']
>>> sort = {'Country': 'Country', 'Channel': 'Size', 'Genre': 'Prev'}
>>> subtotal(data, columns, agg='sum', sort=sort)
    Country  Channel    Genre  Size  Prev
0   UK       Stores     Blues   20    12
1   UK       Stores     Rock    35    30
2   UK       Stores             55    42
3   UK       Partners   Blues   25    20
4   UK       Partners   Rock    55    50
5   UK       Partners           80    70
6   UK                         135   112
7   US       Stores     Rock    45    40
8   US       Stores             45    40
9   US       Partners   Rock    65    60
10  US       Partners           65    60
11  US                         110   100
12                             245   212

在这个:

  • “国家/地区”列按国家/地区名称升序排序(英国在美国之前)
  • “渠道”列按大小升序排序(在国家/地区内)(英国商店 = 55,然后英国合作伙伴 = 80)
  • “流派”列按 Prev 升序排序(在 Country 和 Genre 内)(UK Stores Blues = 20,UK Stores Rock = 35)

我们怎样才能有效地做到这一点?

【问题讨论】:

    标签: python pandas pandas-groupby pivot-table


    【解决方案1】:

    这是一个非常原始的分步脚本,但是在聚合重复属性的数据后,它会添加总和。然后它为每个属性组合和排序分组的行。

    df = df.groupby(['Country','Channel','Genre'], as_index=False)[['Size','Prev']].sum()
    df.loc['all_total'] = df.sum(numeric_only=True, axis=0)
    sub1 = df.groupby('Country', as_index=False)[['Size','Prev']].sum()
    sub2 = df.groupby(['Country','Channel'], as_index=False)[['Size','Prev']].sum()
    all_total = pd.concat([df, sub1, sub2], axis=0)
    all_total.sort_values(['Country','Channel'], ascending=[True,False],axis=0).fillna('')
    
        Country     Channel     Genre   Size    Prev
    2   UK  Stores  Blues      20.0     12.0
    3   UK  Stores  Rock       35.0     30.0
    1   UK  Stores             55.0     42.0
    0   UK  Partners    Blues   25.0    20.0
    1   UK  Partners    Rock    55.0    50.0
    0   UK  Partners           80.0     70.0
    0   UK                    135.0     112.0
    5   US  Stores  Rock      45.0  40.0
    3   US  Stores            45.0  40.0
    4   US  Partners    Rock    65.0    60.0
    2   US  Partners           65.0     60.0
    1   US                     110.0    100.0
    all_total                  245.0    212.0
    

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 2015-06-20
      • 1970-01-01
      • 2023-03-18
      • 2014-01-05
      • 2020-02-14
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      相关资源
      最近更新 更多