I have an excel spreadsheet with key columns (k1, k2) and amount columns (a1 thru a12).
I need to group by k1, k2 and in the resulting dataframe sum the columns and save the amounts to a new column. Here is what I have tried so far
import numpy as nm
import pandas as pd
df = pd.read_excel('C:\Users\pb\Desktop\py test\Bal.xlsx')
df1=df.groupby(['k1', 'k2'])
#sum a1 thru a12(also tried df['suma'] = df['a1']+df['a2']
df1['suma']=df1.apply(lambda x: x['a1'] + x['a2'])
Here is the error I am getting
TypeErrorTraceback (most recent call last) <ipython-input-14-242ac0584a79> in <module>()
3 df1=df.groupby(['k1', 'k2'])
4 #sum a1 thru a12
----> 5 df1['sum']=df1.apply(lambda x: x['a1'] + x['a2'])
TypeError: 'DataFrameGroupBy' object does not support item assignment
Is there a way to sum the columns after the group by?
Thanks in advance