Skip to content
Advertisement

Custom Column Selection in Pandas DataFrame.Groupby.Agg’s dictionary

I have a problem in selecting what columns to be inserted in Pandas.DataFrame.Groupby.agg.

Here’s the code to get and prepare the data.

JavaScript

Which results in

What I’ve done so far is

JavaScript

that results in:

The question is:

  1. How do I include other non numeric columns?
  2. How do I include other undetermined columns in the dictionary and set the method as ‘mean’?

Advertisement

Answer

1) To determine if a column is numeric, you can use pandas.api.types.is_numeric_dtype

2) To find the remaining columns, you can use set(df.columns) minus the columns you used in groupby and those with specific agg functions, for example

JavaScript

after that, combine the set of fields_specific and fields_agg_remaining to be the agg fields list

JavaScript

EDIT: You can combine everything to put them inside the dictionary argument, for example:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement