Pandas: How to Sum Columns Based on a Condition


You can use the following syntax to sum the values of a column in a pandas DataFrame based on a condition:

df.loc[df['col1'] == some_value, 'col2'].sum()

This tutorial provides several examples of how to use this syntax in practice using the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'C'],
                   'conference': ['East', 'East', 'East', 'West', 'West', 'East'],
                   'points': [11, 8, 10, 6, 6, 5],
                   'rebounds': [7, 7, 6, 9, 12, 8]})

#view DataFrame
df

        team	conference  points  rebounds
0	A	East	    11	    7
1	A	East	    8	    7
2	A	East	    10	    6
3	B	West	    6	    9
4	B	West	    6	    12
5	C	East	    5	    8

Example 1: Sum One Column Based on One Condition

The following code shows how to find the sum of the points for the rows where team is equal to ‘A’:

df.loc[df['team'] == 'A', 'points'].sum()

29

Example 2: Sum One Column Based on Multiple Conditions 

The following code shows how to find the sum of the points for the rows where team is equal to ‘A’ and where conference is equal to ‘East’:

df.loc[(df['team'] == 'A') & (df['conference'] == 'East'), 'points'].sum()

29

Example 3: Sum One Column Based on One of Several Conditions

The following code shows how to find the sum of the points for the rows where team is equal to ‘A’ or ‘B’:

df.loc[df['team'].isin(['A', 'B']), 'points'].sum()

41

You can find more pandas tutorials on this page.

Leave a Reply

Your email address will not be published.