pandas, apply multiple functions of multiple columns to groupby object

前端 未结 6 1372
迷失自我
迷失自我 2021-02-13 12:55

I want to apply multiple functions of multiple columns to a groupby object which results in a new pandas.DataFrame.

I know how to do it in seperate steps:

6条回答
  •  故里飘歌
    2021-02-13 12:59

    Another solid variation of the solution is to do what @MaxU did with this solution to a similar question and wrap the individual functions in a Pandas series, thus only requiring a reset_index() to return a dataframe.

    First, define the functions for transformations:

    def ed(group):
        return group.elapsed_time * group.num_cores).sum() / 86400
    
    def rd(group):
        return group.running_time * group.num_cores).sum() / 86400
    

    Wrap them up in a Series using get_stats:

    def get_stats(group):
        return pd.Series({'elapsed_days': ed(group),
                          'running_days':rd(group)})
    

    Finally:

    lasts.groupby('user').apply(get_stats).reset_index()
    

提交回复
热议问题