Group-by and Sum in Python Pandas

PythonServer Side ProgrammingProgramming

To find group-by and sum in Python Pandas, we can use groupby(columns).sum().

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
  • Print the input DataFrame, df.
  • Find the groupby sum using df.groupby().sum(). This function takes a given column and sorts its values. After that, based on the sorted values, it also sorts the values of other columns.
  • Print the groupby sum.

Example

import pandas as pd

df = pd.DataFrame(
    {
       "Apple": [5, 2, 7, 0],
       "Banana": [4, 7, 5, 1],
       "Carrot": [9, 3, 5, 1]
    }
)

print "Input DataFrame 1 is:\n", df
g_sum = df.groupby(['Apple']).sum()
print "Group by Apple is:\n", g_sum

Output

Input DataFrame 1 is:

   Apple Banana Carrot
0    5     4      9
1    2     7      3
2    7     5      5
3    0     1      1

Group by Apple is:

Apple Banana Carrot
0       1      1
2       7      3
5       4      9
7       5      5
raja
Published on 14-Sep-2021 11:52:59
Advertisements