Can columns be summed in Pandas based on a condition?

Pandas is a popular data analysis library in Python that provides powerful tools for manipulating and analyzing data. One of its key functions is the ability to sum columns in a DataFrame based on a given condition. This means that users can specify a certain criteria or condition, and Pandas will only sum the values in the selected columns that meet that condition. This feature allows for efficient and targeted data analysis, as it eliminates the need to manually filter and sum data. With Pandas, users can easily perform complex calculations and derive insights from their data by summing columns based on specific conditions.

Pandas: 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 .

x