Need help on agg function after groupby for doing operation last - first

Viewed 114

I've below pandas dataframe.

  group   A   B   C   D   E
0    g1  12  14  26  68  83
1    g1  56  58  67  34  97
2    g1  47  87  23  87  90
3    g2  43  76  98  32  78
4    g2  32  56  36  87  65
5    g2  54  12  24  45  95

I wish to apply groupby on same using column 'group' and wish to apply aggregate function to get (last - first) for column 'E'.

The expected output:

  group   A   B    C   D  E
0    g1  12  87  116  34  7
1    g2  43  12  158  32  17

I've written below code. But it is not working.

import pandas as pd

df = pd.DataFrame([["g1", 12, 14, 26, 68, 83], ["g1", 56, 58, 67, 34, 97], ["g1", 47, 87, 23, 87, 90], ["g2", 43, 76, 98, 32, 78], ["g2", 32, 56, 36, 87, 65], ["g2", 54, 12, 24, 45, 95]], columns=["group", "A", "B", "C", "D", "E"])
ndf = df.groupby(["group"], as_index=False).agg({"A": 'first', "B": 'last', "C": 'sum', "D": 'min', "E": 'last - first'})
print(df)
print(ndf)
1 Answers

You can use a lambda function for this.

ndf = (
    df.groupby(["group"], as_index=False)
    .agg({"A": 'first',
          "B": 'last',
          "C": 'sum',
          "D": 'min',
          "E": lambda x: x.iat[-1]-x.iat[0]})
)

will output

  group   A   B    C   D   E
0    g1  12  87  116  34   7
1    g2  43  12  158  32  17
Related