Excel SUMIFS, COUNTIFS and AVERAGEIFS in Python (Pandas)
In pandas, SUMIF is a filter followed by sum(): df.query(‘Country == “Germany”‘)[“Sales”].sum(). COUNTIF and AVERAGEIF use count() and mean() on the same filter. For SUMIFS, COUNTIFS and AVERAGEIFS, join several conditions with & inside query. groupby() returns the result for every category at once, like a pivot table.
Load the sales data
The examples use the Financial Sample workbook that Microsoft publishes for Power BI: 700 rows of fictional sales by country, segment and product. Load it into a DataFrame called df with read_excel().
import pandas as pd # pip install pandas openpyxl
from pathlib import Path # standard python module
# Display only one decimal place
pd.set_option('display.float_format', '{:.1f}'.format)
EXCEL_FILE_PATH = Path.cwd() / 'Financial_Sample.xlsx'
df = pd.read_excel(EXCEL_FILE_PATH)
df.columns = df.columns.str.strip() # the sample file has " Sales" with a leading space
df.head()
Download the file from Microsoft’s sample page and save it as Financial_Sample.xlsx next to your script. Its Sales header has a leading space, so the script strips the column names after loading. Without that line, df[“Sales”] raises a KeyError.
SUM, AVERAGE and COUNT
Select the column and call sum(), mean() or count(). These match SUM, AVERAGE and COUNT over a whole column in Excel.
# Sum
df['Sales'].sum()
# Average
df['Sales'].mean()
# Count
df['Sales'].count()
118726350.25999999
169609.07179999998
700
SUMIF, AVERAGEIF and COUNTIF
A conditional formula in Excel is a filter plus a calculation in pandas. query() keeps the rows that match the condition, and the method at the end does the math. This is SUMIF, AVERAGEIF and COUNTIF for Germany:
# SumIf
sumif = df.query('Country == "Germany"')['Sales'].sum()
sumif
# AverageIf
averageif = df.query('Country == "Germany"')['Sales'].mean()
averageif
# CountIf
countif = df.query('Country == "Germany"')['Sales'].count()
countif
Sales for Germany add up to:
23505340.82
SUMIFS, AVERAGEIFS and COUNTIFS
For several criteria, join the conditions with & inside the query string. This returns the sales for Germany in the Midmarket segment:
# SumIfs
sumifs = df.query('Country == "Germany" & Segment == "Midmarket"')['Sales'].sum()
sumifs
# AverageIfs
averageifs = df.query('Country == "Germany" & Segment == "Midmarket"')['Sales'].mean()
averageifs
# CountIfs
countifs = df.query('Country == "Germany" & Segment == "Midmarket"')['Sales'].count()
countifs
301344.75
To keep the criteria out of the string, store them in variables and refer to them with @. Here @country becomes Germany and @segment Midmarket:
country = "Germany"
segment = "Midmarket"
sumifs = df.query('Country == @country & Segment == @segment')['Sales'].sum()
sumifs
Every category at once
groupby() calculates the result for every value in a column, like a pivot table with that column in the rows. Group by several columns, such as country and segment, for a SUMIFS over every combination.
In pandas 2 and later, pass numeric_only=True when you sum the whole frame, because the sample file has a Date column that cannot be summed. Selecting the Sales column first avoids the issue.
df.groupby(by=['Country']).sum(numeric_only=True)
df.groupby(by=['Country'])[['Sales']].sum()
df.groupby(by=['Country', 'Segment'])[['Sales']].sum()
Units Sold Manufacturing Price Sale Price Gross Sales Discounts Sales COGS Profit Month Number Year
Country
Canada 247428.5 13150 16580 26932163.5 2044508.615 2.488765e+07 21358426.0 3529228.885 1106 281925
France 240931.0 13374 16580 26081674.5 1727502.220 2.435417e+07 20573151.5 3781020.780 1106 281925
Germany 201494.0 13370 16580 24921467.5 1416126.680 2.350534e+07 19824952.0 3680388.820 1106 281925
Mexico 203325.0 13394 16580 22726935.0 1777582.890 2.094935e+07 18041829.0 2907523.110 1106 281925
United States of America 232627.5 14246 16580 27269358.0 2239527.835 2.502983e+07 22034289.5 2995540.665 1106 281925
Excel to pandas cheat sheet
Each Excel formula below has a one-line pandas equivalent on the same sample data.
| Excel formula | pandas |
|---|---|
=SUM(Sales) |
df["Sales"].sum() |
=SUMIF(Country,"Germany",Sales) |
df.query('Country == "Germany"')["Sales"].sum() |
=COUNTIF(Country,"Germany") |
df.query('Country == "Germany"')["Sales"].count() |
=AVERAGEIF(Country,"Germany",Sales) |
df.query('Country == "Germany"')["Sales"].mean() |
=SUMIFS(Sales,Country,"Germany",Segment,"Midmarket") |
df.query('Country == "Germany" & Segment == "Midmarket"')["Sales"].sum() |
| Pivot table with Country in rows | df.groupby("Country")["Sales"].sum() |
Full script
Every calculation from this post in one script. I tested it with pandas 2.2 and the Microsoft Financial Sample file in November 2026.
import pandas as pd
from pathlib import Path
EXCEL_FILE_PATH = Path.cwd() / "Financial_Sample.xlsx"
df = pd.read_excel(EXCEL_FILE_PATH)
df.columns = df.columns.str.strip() # the sample file has " Sales" with a leading space
# SUM, AVERAGE, COUNT
total = df["Sales"].sum()
average = df["Sales"].mean()
count = df["Sales"].count()
# SUMIF, AVERAGEIF, COUNTIF
sumif = df.query('Country == "Germany"')["Sales"].sum()
averageif = df.query('Country == "Germany"')["Sales"].mean()
countif = df.query('Country == "Germany"')["Sales"].count()
# SUMIFS, AVERAGEIFS, COUNTIFS
country = "Germany"
segment = "Midmarket"
sumifs = df.query("Country == @country & Segment == @segment")["Sales"].sum()
averageifs = df.query("Country == @country & Segment == @segment")["Sales"].mean()
countifs = df.query("Country == @country & Segment == @segment")["Sales"].count()
# Pivot-style summary: SUMIFS for every combination
summary = df.groupby(["Country", "Segment"])["Sales"].sum()
Column names with spaces
query() only understands plain names like Country. For a column such as “Discount Band”, wrap the name in backticks inside the query string, for example df.query("`Discount Band` == 'High'"). Or skip query and use a boolean mask, which works with any column name: df.loc[(df["Country"] == "Germany") & (df["Segment"] == "Midmarket"), "Sales"].sum(). Note the brackets around each condition. Without them, Python applies & before == and you get an error.
COUNTIF counts rows, while count() skips empty cells in the column you pick. If your Sales column has gaps, use len(df.query(...)) to match Excel.
The next Excel habit to replace is the lookup: see how to do a VLOOKUP in pandas. If your source file has titles and blank rows above the table, start with how to read messy Excel files with pandas.
