pandas default aggregation function for rest of the columns

Question:

I’d need to groupby and aggregate dataframe.

Some columns have specific aggregation function, for the rest I’d like to use first.

I just don’t want to hardcode the rest of column names, because it can differ by case. Do you have any elegant idea how to achieve that?

import pandas as pd

df = pd.DataFrame({"col1": [1,2,3,4,5],
                   "col2": ["aa","aa","bb","bb","cc"],
                   "col3": ["b","b","b","b","b"],
                   "col4": ["c","c","c","c","c"],
                   "col5": [11,12,13,14,15]}
                  )

df.groupby(["col2"]).agg({
                          "col1": "mean",
                          "col5": "max",
                          "col3": "first",
                          "col4": "first"
                          })

output:

      col1  col5 col3 col4
col2
aa     1.5    12    b    c
bb     3.5    14    b    c
cc     5.0    15    b    c

but I don’t want to explicitly specify

                          "col3": "first",
                          "col4": "first"

Simply all the columns not used in groupby and agg should be aggregated with default function.

Asked By: Honza S.

||

Answers:

You can create dictionary dynamic – first define non first aggregations and then for all columns without column used for groupby and keys from d:

d = {"col1": "mean", "col5": "max"}

agg = {**d, **dict.fromkeys(df.columns.difference(['col2'] + list(d.keys())), 'first')}
print (agg)
{'col1': 'mean', 'col5': 'max', 'col3': 'first', 'col4': 'first'}

Or create dictionary by all values without groupby column(s) and set different aggregations:

agg = dict.fromkeys(df.columns.difference(['col2']), 'first')
agg['col1'] = 'mean'
agg['col5'] = 'max'
print (agg)
{'col1': 'mean', 'col3': 'first', 'col4': 'first', 'col5': 'max'}

df = df.groupby(["col2"]).agg(agg)
print (df)
      col1  col5 col3 col4
col2                      
aa     1.5    12    b    c
bb     3.5    14    b    c
cc     5.0    15    b    c
Answered By: jezrael

You can set up a dictionary with a default function and customize the specific column:

d = {c: 'first' for c in df.columns}
d['col1'] = 'mean'
d['col5'] = 'max'
# or 
d = {c: 'first' for c in df.columns}
d.update({'col1': 'mean', 'col5': max})

del d['col2'] # if you don't want col2 as column

out = df.groupby(["col2"]).agg(d)

output:

      col1 col3 col4  col5
col2                           
aa     1.5    b    c    12
bb     3.5    b    c    14
cc     5.0    b    c    15
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.