'How to apply function to GroupBy agg

I have the following groupby which does not work well since I want to sum absolute values.

DF.groupby(["Name"], as_index=False).agg({"A":"sum",'B': 'first'}).round(2)

How can I add a rule which convert value to absolute before doing the sum ?

Name A B
Test 3 Blabla
Test -3

The output I currently have is

Name A B
Test 0 Blabla

The Excepted output is

Name A B
Test 6 Blabla

How would I apply a function that take the absolute values and then sum these ?

.apply(lambda Nb: Nb.abs().sum())

Note that I know how to do It without agg :

DF.groupby(["Name"], as_index=False)['A'].apply(lambda Nb: Nb.abs().sum()).round(2)


Solution 1:[1]

You might provide functions as values of dict you are passing to pandas.DataFrame.agg, consider following example

import pandas as pd
df = pd.DataFrame({'Name':['A','A','B','B','C','C'],'Value':[-1,2,-3,4,-5,6]})
grouped = df.groupby('Name').agg({'Value':lambda x:sum(abs(x))})
print(grouped)

output

      Value
Name
A         3
B         7
C        11

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daweo