4

Variations of this question have been asked (see this question) but I haven't found a good solution for would seem to be a common use-case of groupby in Pandas.

Say I have the dataframe lasts and I group by user:

lasts = pd.DataFrame({'user':['a','s','d','d'],
                   'elapsed_time':[40000,50000,60000,90000],
                   'running_time':[30000,20000,30000,15000],
                   'num_cores':[7,8,9,4]})

And I have these functions I want to apply to groupby_obj (what the functions do isn't important and I made them up, just know that they require multiple columns from the dataframe):

def custom_func(group):
    return group.running_time.median() - group.num_cores.mean()

def custom_func2(group):
    return max(group.elapsed_time) -min(group.running_time) 

I could apply each of these functions separately to the dataframe and then merge the resulting dataframes, but that seems inefficient, is inelegant, and I imagine there has to be a one-line solution.

I haven't really found one, although this blog post (search for "Create a function to get the stats of a group" towards the bottom of the page) suggested wrapping the functions into one function as a dictionary thusly:

def get_stats(group):
    return {'custom_column_1': custom_func(group), 'custom_column_2':custom_func2(group)}

However, when I run the code groupby_obj.apply(get_stats), instead of columns I get a column of dictionary results:

user
a    {'custom_column_1': 29993.0, 'custom_column_2'...
d    {'custom_column_1': 22493.5, 'custom_column_2'...
s    {'custom_column_1': 19992.0, 'custom_column_2'...
dtype: object

When in reality I would like to use a line of code to get something closer to this dataframe:

user custom_column_1    custom_column_2
a    29993.0                10000
d    22493.5                75000
s    19992.0                30000

Suggestions on improving this workflow?

Community
  • 1
  • 1
zthomas.nc
  • 3,689
  • 8
  • 35
  • 49

2 Answers2

5

Consider the following approach:

funcs = {
  'running_time': {'rt_med':'median', 'rt_min':'min'},
  'num_cores': {'nc_avg':'mean'},
  'elapsed_time': {'et_max':'max'}
}

x = lasts.groupby('user').agg(funcs)
x.columns = x.columns.droplevel(0)

formulas = """
custom_column_1 = rt_med - nc_avg
custom_column_2 = et_max - rt_min

"""

res = x.eval(formulas, inplace=False).drop(x.columns, 1).reset_index()

Result:

In [145]: res
Out[145]:
  user  custom_column_1  custom_column_2
0    a          29993.0            10000
1    d          22493.5            75000
2    s          19992.0            30000

Explanation (step by step):

In [146]: x = lasts.groupby('user').agg(funcs)

In [147]: x
Out[147]:
     running_time        num_cores elapsed_time
           rt_med rt_min    nc_avg       et_max
user
a           30000  30000       7.0        40000
d           22500  15000       6.5        90000
s           20000  20000       8.0        50000

In [148]: x.columns = x.columns.droplevel(0)

In [149]: x
Out[149]:
      rt_med  rt_min  nc_avg  et_max
user
a      30000   30000     7.0   40000
d      22500   15000     6.5   90000
s      20000   20000     8.0   50000

In [150]: x.eval(formulas, inplace=False)
Out[150]:
      rt_med  rt_min  nc_avg  et_max  custom_column_1  custom_column_2
user
a      30000   30000     7.0   40000          29993.0            10000
d      22500   15000     6.5   90000          22493.5            75000
s      20000   20000     8.0   50000          19992.0            30000

In [151]: x.eval(formulas, inplace=False).drop(x.columns, 1)
Out[151]:
      custom_column_1  custom_column_2
user
a             29993.0            10000
d             22493.5            75000
s             19992.0            30000

In [152]: x.eval(formulas, inplace=False).drop(x.columns, 1).reset_index()
Out[152]:
  user  custom_column_1  custom_column_2
0    a          29993.0            10000
1    d          22493.5            75000
2    s          19992.0            30000
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
3

If you would slightly modify the get_stats function:

def get_stats(group):
    return pd.Series({'custom_column_1': custom_func(group),
                      'custom_column_2':custom_func2(group)})

now you can simply do this:

In [202]: lasts.groupby('user').apply(get_stats).reset_index()
Out[202]:
  user  custom_column_1  custom_column_2
0    a          29993.0          10000.0
1    d          22493.5          75000.0
2    s          19992.0          30000.0

Alternative (bit ugly) approach which uses your functions (unchanged):

In [188]: pd.DataFrame(lasts.groupby('user')
                            .apply(get_stats).to_dict()) \
            .T \
            .rename_axis('user') \
            .reset_index()
Out[188]:
  user  custom_column_1  custom_column_2
0    a          29993.0          10000.0
1    d          22493.5          75000.0
2    s          19992.0          30000.0
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419