Asif Iqbal
Asif Iqbal

Reputation: 511

Applying user provided function on groupby object

I have a dataframe:

pri_col col1 col2        Date
     r1    3    4  2020-09-10
     r1    4    1  2020-09-10
     r2    2    7  2020-09-11
     r2    6    4  2020-09-11

I am performing a groupby on pri_col and date columns and then applying a function on the rest of the columns.

But the issue here is that I need to take the function as input from the user. Eg.

func = input('Function to use: ')
ret_df = ip_df.groupby(['pri_col','date']).apply(eval(func))

But this applies the function on pri_col and date also, which is not desired.

Eg. If user provides 'sum' as input, I want the final output to be like,

pri_col col1 col2        Date
     r1    7    5   2020-09-10
     r2    8    11  2020-09-11

Is there any other approach to this problem? I have tried removing .apply() and using .eval() directly, but we can't do that to groupby object.

Upvotes: 1

Views: 28

Answers (1)

jezrael
jezrael

Reputation: 862581

Use this trick - convert columns to MultiIndex, so not processing by function:

ret_df = ip_df.set_index(['pri_col','date']).groupby(['pri_col','date']).apply(eval(func))

For oldier pandas version use:

ret_df = ip_df.set_index(['pri_col','date']).groupby(level=[0, 1]).apply(eval(func))

Upvotes: 1

Related Questions