【问题标题】:Filter | Groupby | Aggregate过滤器 |分组 |总计的
【发布时间】:2021-09-22 21:06:18
【问题描述】:

我在 pandas python 中做一些任务。

我有这样的数据:

col1  |col2  |col3 |col4 |col5 | col6
delhi |assam |"f"  |78.3 |87.1 | B2C
delhi |goa   |"f"  |78.3 |87.1 | B2C
delhi |goa   |"f"  |78.3 |87.1 | B2C
delhi |assam |"f"  |78.3 |87.1 | B2C
up    |assam |"f"  |78.3 |87.1 | B2B
delhi |assam |"f"  |78.3 |87.1 | B2B

现在我想过滤 col6 为 B2C 的那些行。 过滤后,我想对 col1 和 col2 进行分组并对 col4 和 col5 求和。

所以输出应该是这样的:

col1  |col2  |col3 |col4 |col5 | col6
delhi |assam |"f"  |156.6|174.2| B2C
delhi |goa   |"f"  |156.6|174.2| B2C
up    |assam |"f"  |78.3 |87.1 | B2B
delhi |assam |"f"  |78.3 |87.1 | B2B

我尝试过的方法:

df.loc[df['col6'] == 'B2C'].groupby(['col1', 'col2']).agg({'col4':'sum', 'col5':'sum'})

但我不知道如何将此结果附加到原始数据框。如果我能做得比这更好,也请指导我。

【问题讨论】:

    标签: python pandas pandas-groupby aggregate


    【解决方案1】:

    IIUC,这是一种方法:

    df = df.groupby(['col1', 'col2', 'col3','col6'], sort=False).sum().reset_index()
    

    注意:如果您只想执行聚合,其中 col6 中的值是 eq ('B2C')

    df = pd.concat([df[df.col6.eq('B2C')].groupby(['col1', 'col2', 'col3'],sort=False).sum().reset_index().assign(col6 = 'B2C'), df[df.col6.ne('B2C')]])
    

    输出:

         col1    col2 col3  col6   col4   col5
    0  delhi   assam   f     B2C  156.6  174.2
    1  delhi   goa     f     B2C  156.6  174.2
    2  up      assam   f     B2B   78.3   87.1
    3  delhi   assam   f     B2B   78.3   87.1
    

    【讨论】:

    • 我们是否需要在 groupby 中也使用 col3 ?
    • 另外,如果我有 100 列,我只需要对 2 列进行分组并在 3 列上进行聚合,那么我需要在 groupby 中提及其他 95 列,或者有一些方便的方法可以做到这一点?
    • 在我的情况下,col6 在列名中也有空格,如“col 6”。如何在分配中放置带有空格的列名?
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多