Instagram
youtube
Facebook
Twitter

Compute Sum of Each Group in Pandas DataFrame

A Compute Sum of Each Group in Pandas DataFrame?

Code Explanation:
● Library Import: pandas is imported as pd.
● DataFrame Creation: A DataFrame with columns 'Group' and 'Value' is created.
● Grouping: Data is grouped by the 'Group' column.
● Aggregation: The sum of each group is calculated using .sum().
● Store Result: Group-wise sum is stored in group_sum.
● Output Display: Sum values are printed.

 

Program:

import pandas as pd

df = pd.DataFrame({

    'Group': ['A', 'A', 'B', 'B'],

    'Value': [10, 20, 30, 40]

})


group_sum = df.groupby('Group')['Value'].sum()

print(group_sum)