Most pythonic way to sum rows in a dataframe based on index groups

jAg*_*ses 2 python pandas

I have the following pandas dataframe:

df = pd.DataFrame([[1,2,3,'a'],[4,5,6,'a'],[2,4,1,'a'],[2,4,1,'b'],[4,9,6,'b'],[2,4,1,'b']], index=[0,1,2,0,1,2], columns=['aa','bb','cc','cat'])


     aa    bb    cc    cat
0    1      2     3    a
1    4      5     6    a
2    2      4     1    a
0    2      4     1    b
1    4      9     6    b
2    2      4     1    b
Run Code Online (Sandbox Code Playgroud)

I need to add rows with the same index.

    aa   bb   cc  cat
0   3    6    4    ab
1   8   14   12    ab
2   4    8    2    ab
Run Code Online (Sandbox Code Playgroud)

I used the following code:

df_ab = df[df['cat'] == 'a'] + df[df['cat'] == 'b']
Run Code Online (Sandbox Code Playgroud)

But is this the most pythonic way ?

raf*_*elc 5

Use groupby and agg

df.groupby(df.index).agg({'aa': 'sum',
                          'bb': 'sum',
                          'cc': 'sum',
                          'cat': ''.join})
Run Code Online (Sandbox Code Playgroud)

Or pass numeric_only=False (simpler, but I wouldn't recommend)

df.groupby(df.index).sum(numeric_only=False)
Run Code Online (Sandbox Code Playgroud)

Both output

    aa  bb  cc cat
0   3   6   4  ab
1   8  14  12  ab
2   4   8   2  ab
Run Code Online (Sandbox Code Playgroud)