Python for Excel users · Lesson 8 of 14

SUMIF, COUNTIF and SUMIFS in pandas

Write SUMIF, COUNTIF, SUMIFS, COUNTIFS, AVERAGEIFS and MAXIFS in pandas with masks, and get a whole summary table at once with groupby.

About 16 minutes · code runs in your browser, nothing to install

Conditional sums are Excel's everyday reporting tool: =SUMIF(A:A, "North", C:C) adds the sales of one region. In pandas you first pick the rows with a mask (as in Filter and sort data like Excel AutoFilter), then sum, count or average the column you want.

SUMIF and COUNTIF

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Region": ["North", "South", "North", "East", "South", "North"],
    "Product": ["Lamp", "Desk", "Desk", "Lamp", "Lamp", "Lamp"],
    "Sales": [120, 340, 410, 95, 150, 80],
})

north = df["Region"] == "North"
print("SUMIF:", df.loc[north, "Sales"].sum())
print("COUNTIF:", north.sum())
print("COUNTIF >100:", (df["Sales"] > 100).sum())
Output
SUMIF: 610
COUNTIF: 3
COUNTIF >100: 4

df.loc[mask, "Sales"] means: these rows, that column. Summing a mask counts its True values, because True counts as 1.

SUMIFS, COUNTIFS, AVERAGEIFS and MAXIFS

Several criteria are several masks joined with &. =SUMIFS(C:C, A:A, "North", B:B, "Lamp") becomes:

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Region": ["North", "South", "North", "East", "South", "North"],
    "Product": ["Lamp", "Desk", "Desk", "Lamp", "Lamp", "Lamp"],
    "Sales": [120, 340, 410, 95, 150, 80],
})

rows = (df["Region"] == "North") & (df["Product"] == "Lamp")
print("SUMIFS:", df.loc[rows, "Sales"].sum())
print("COUNTIFS:", rows.sum())
print("AVERAGEIFS:", df.loc[rows, "Sales"].mean())
print("MAXIFS:", df.loc[rows, "Sales"].max())
Output
SUMIFS: 200
COUNTIFS: 2
AVERAGEIFS: 100.0
MAXIFS: 120

Criteria such as ">=100" or "<>East" are ordinary comparisons in pandas: df["Sales"] >= 100 and df["Region"] != "East". A wildcard like "L*" is df["Product"].str.startswith("L"). One difference: Excel criteria ignore upper and lower case, pandas comparisons do not, so "north" does not match "North" (use .str.lower() on the column first if the case varies).

A SUMIF for every value at once: groupby

In Excel you would list the regions in a column and fill a SUMIF next to them. groupby does the whole table in one line: it groups rows with the same value and adds up each group.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Region": ["North", "South", "North", "East", "South", "North"],
    "Product": ["Lamp", "Desk", "Desk", "Lamp", "Lamp", "Lamp"],
    "Sales": [120, 340, 410, 95, 150, 80],
})

print(df.groupby("Region")["Sales"].sum())
Output
Region
East      95
North    610
South    490
Name: Sales, dtype: int64

The result is sorted A to Z by region. Add .sort_values(ascending=False) to put the biggest first.

agg gives several results per group, each with its own column name: a SUMIF, a COUNTIF and an AVERAGEIF side by side.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Region": ["North", "South", "North", "East", "South", "North"],
    "Product": ["Lamp", "Desk", "Desk", "Lamp", "Lamp", "Lamp"],
    "Sales": [120, 340, 410, 95, 150, 80],
})

summary = df.groupby("Region").agg(
    Total=("Sales", "sum"),
    Orders=("Sales", "count"),
    Average=("Sales", "mean"),
)
print(summary.round(1))
Output
        Total  Orders  Average
Region
East       95       1     95.0
North     610       3    203.3
South     490       2    245.0

Group by two columns for a SUMIFS on every combination. value_counts() is a quick COUNTIF for every value in a column.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "Region": ["North", "South", "North", "East", "South", "North"],
    "Product": ["Lamp", "Desk", "Desk", "Lamp", "Lamp", "Lamp"],
    "Sales": [120, 340, 410, 95, 150, 80],
})

print(df.groupby(["Region", "Product"])["Sales"].sum())
print(df["Product"].value_counts())
Output
Region  Product
East    Lamp        95
North   Desk       410
        Lamp       200
South   Desk       340
        Lamp       150
Name: Sales, dtype: int64
Product
Lamp    4
Desk    2
Name: count, dtype: int64

When you want regions down the side and products across the top, you want a pivot table: next lesson.

✎ Exercise

Print the total Hours for the Design team (a SUMIF), the number of entries with more than 5 hours (a COUNTIF), and then the total hours of every team with groupby.

Hint: df.loc[mask, "Hours"].sum() for the SUMIF, (mask).sum() for the COUNTIF, groupby("Team") for the table.

Your codewrite your answer, then Run
import pandas as pd

df = pd.DataFrame({
    "Team": ["Design", "Web", "Design", "Ops", "Web", "Design"],
    "Hours": [6, 3, 4, 8, 7, 2],
})
# your code here

Expected output:

12
3
Team
Design    12
Ops        8
Web       10
Name: Hours, dtype: int64
Show a solution
Solutioneditable
import pandas as pd

df = pd.DataFrame({
    "Team": ["Design", "Web", "Design", "Ops", "Web", "Design"],
    "Hours": [6, 3, 4, 8, 7, 2],
})
print(df.loc[df["Team"] == "Design", "Hours"].sum())
print((df["Hours"] > 5).sum())
print(df.groupby("Team")["Hours"].sum())
Output
12
3
Team
Design    12
Ops        8
Web       10
Name: Hours, dtype: int64

Check yourself

1. What is the pandas version of =COUNTIF(A:A, "North")?

2. How do you write two criteria for SUMIFS in pandas?

3. What does df.groupby("Region")["Sales"].sum() give?

Spotted a mistake on this page? Tell us