【问题标题】:Pandas Conditional Aggregation and Non Conditional Aggregation togetherPandas 条件聚合和非条件聚合在一起
【发布时间】:2020-02-27 06:52:34
【问题描述】:

我是一个重度 SQL 用户,而且我是 Python 和 Pandas 的新手。我有一个数据框。

import pandas as pd

data=[[1,100,'a'],[1,200,'b'],[2,300,'a'],[2,400,'a'],[3,500,'b'],[3,600,'a'],[3,700,'b']]

df=pd.DataFrame(data,columns=['Group','Amount','Condition'])

我可以一步计算条件和和“常规”和吗?

基本上,在SQL中,会是这样的。

select [Group]
,sum([Amount]) as Amount
,sum(case when [Condition]=’a’ then [Amount] end) as Conditional_Sum
from df
group by [Group]

但在 Pandas 中,我将它们分为几个步骤。

对于“常规”总和,我使用

df1=df.groupby('Group')['Amount'].sum().reset_index()

对于条件和,我使用

df2=df.groupby('Group').apply(lambda x: x[x['Condition']=='a']['Amount'].sum()).to_frame(name='Conditional_Sum')
df2.reset_index(inplace=True)

然后我合并 df1 和 df2。我可以一步完成吗?

编辑:澄清一下,有没有办法在一步内创建下面的数据框?

   Group  Amount  Conditional_Sum
0      1     300              100
1      2     700              700
2      3    1800              600

【问题讨论】:

    标签: python pandas dataframe aggregate-functions aggregation


    【解决方案1】:

    您可以使用 groupby 应用并创建包含某些列的系列

    df.groupby('Group', as_index=False) \
      .apply(lambda x: pd.Series( \
            {'totalsum' : x['Amount'].sum(), \
             'condsum': x.loc[x['Condition']=='a','Amount'].sum()}))
    
           totalsum  condsum
    0       300      100
    1       700      700
    2      1800      600
    

    【讨论】:

    • 谢谢。我喜欢这种方式。
    猜你喜欢
    • 2021-08-24
    • 2018-09-29
    • 2019-08-10
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    相关资源
    最近更新 更多