【问题标题】:Pandas groupby: aggregate only on partial recordsPandas groupby:仅在部分记录上聚合
【发布时间】:2018-09-15 17:50:56
【问题描述】:

我有以下数据框:

id   src     target     duration
001     A      C           4
001     B      C           3
001     C      C           2
002     B      D           5
002     C      D           2

我使用以下代码进行了一些聚合,效果很好。

df_new = df.groupby(['id','target']) \
        .apply(lambda x: pd.Series({'min_duration': min(x['duration']), \
                                    'total_duration':sum(x['duration']), \
                                    'all_src':list(x['src'])
                                   })).reset_index()

现在我只想计算 src != target 记录的总和。我修改了我的代码,如下所示:

df_new = df.groupby(['id','target']) \
        .apply(lambda x: pd.Series({'min_duration': min(x['duration']), \
                                    'total_duration':sum(x['duration']), \
                                    'total_duration_condition':sum(x['duration']) if x['src'] != x['target'], \
                                    'all_src':list(x['src'])
                                   })).reset_index()

然后在我的新行中出现Invalid Syntax 错误:

'total_duration_condition':sum(x['duration']) if x['src'] != x['target']

我想知道仅对部分记录进行求和的正确方法应该是什么?谢谢!

【问题讨论】:

    标签: python-3.x pandas aggregate pandas-groupby


    【解决方案1】:

    尝试编写如下代码

    df.groupby(['id','target']).apply(lambda x: pd.Series({'min_duration': min(x['duration']), \
                                        'total_duration':sum(x['duration']), \
                                        'total_duration_condition':sum(x['duration'][x['src'] != x['target']]), \# I change this part
                                        'all_src':list(x['src'])
                                       })).reset_index()
    

    换行

    'total_duration_condition':sum(x['duration']) if x['src'] != x['target']
    

    sum(x['duration'][x['src'] != x['target']])
    

    【讨论】:

      猜你喜欢
      • 2016-01-27
      • 2014-11-23
      • 2022-01-21
      • 2019-08-10
      • 2017-11-03
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多