Issue
Here is my dataframe for example
df = pd.DataFrame({'name': ['adam', 'adam', 'adam'],
'meal': ['breakfast', 'lunch', 'dinner'],
'cost': [75, 120, 250]})
name meal cost
0 adam breakfast 75
1 adam lunch 120
2 adam dinner 250
How can I get sum of all meals and insert to the last row and add a percentage column, as follows
name meal cost percent
0 adam breakfast 75 16.85
1 adam lunch 120 26.97
2 adam dinner 250 56.18
3 adam total 445
I tried to use cumsum()
but it ended like this
df['total'] = df.groupby('name').cumsum()
name meal cost total
0 adam breakfast 75 75
1 adam lunch 120 195
2 adam dinner 250 445
Solution
You can compute percentage
then add one row with value at the end of dataframe.
sum_cost = df['cost'].sum()
df['percent'] = df['cost'] / sum_cost * 100
df.loc[len(df)] = ['adam', 'total'] + [sum_cost, df['percent'].sum()]
print(df)
Output:
name meal cost percent
0 adam breakfast 75 16.853933
1 adam lunch 120 26.966292
2 adam dinner 250 56.179775
3 adam total 445 100.000000
Answered By - I'mahdi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.