Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas default aggregation function for rest of the columns

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading