4 C
London
Friday, December 20, 2024
HomeStatistics TutorialStatologyPandas: How to Sum Columns Based on a Condition

Pandas: How to Sum Columns Based on a Condition

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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.

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories