Adding Total Row To A Pandas Dataframe With Tuples Inside
Here is my previous question (that has been answered). It helped me for my initial problem but now I am stuck on another one. I have this below pandas.DataFrame which I try to add
Solution 1:
Use:
#s=df.groupby(['Level', 'Company', 'Item'])['Value'].sum()defGetTupleSum(x):
returntuple(sum(y) for y inzip(*x.dropna()))
df= s.unstack('Item')
df['total']=df.apply(GetTupleSum,axis=1)
( df.unstack()
.assign(total_company=df['total'].groupby(level=0).apply(GetTupleSum) )
.stack(['Company','Item']) )
Output
Level Company Item
1 X a (10, 20)
b (10, 20)
total (20, 40)
Y a (10, 20)
b (10, 20)
c (10, 20)
total (30, 60)
total_company (50, 100)
2 X a (10, 20)
b (10, 20)
c (10, 20)
total (30, 60)
Y a (10, 20)
total (10, 20)
total_company (40, 80)
dtype: object
Post a Comment for "Adding Total Row To A Pandas Dataframe With Tuples Inside"