October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Count Rows With Conditions in Pandas

Use a Boolean mask and sum its true values to count matching pandas rows. For grouped counts, choose groupby().size() rather than count() when you mean records.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create a Boolean mask from the condition, then sum it to count matching rows. If you also need the matching records, filter the DataFrame and count the result.

Count rows that meet one condition

A comparison on a DataFrame column produces a Boolean Series with one value for each row. For example, to count rows where score is at least 80:

As an Amazon Associate I earn from qualifying purchases.

mask = df["score"].ge(80)
count = int(mask.sum())

The mask contains True for matching rows and False otherwise. Summing it counts the true values; wrapping the result in int() gives you a regular Python integer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If you want the filtered rows as well as their count, use the same mask to select them:

matching_rows = df.loc[mask]
count = len(matching_rows)
# Equivalent:
count = matching_rows.shape[0]

Boolean indexing keeps rows where the condition is true. See pandas’ selection and indexing guide.

Combine conditions

Use & for AND, | for OR, and ~ for NOT. Put parentheses around each comparison so Python evaluates the comparisons before combining their masks.

Require both conditions

mask = (df["age"] >= 18) & (df["country"] == "US")
count = int(mask.sum())

Match either condition

mask = (df["status"] == "active") | (df["priority"] == "high")
count = len(df.loc[mask])

Exclude a condition

mask = ~(df["status"] == "cancelled")
count = int(mask.sum())

For a column that should match one of several values, use .isin():

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
mask = df["country"].isin(["US", "CA"])
count = int(mask.sum())

The pandas indexing guide covers selecting rows by conditions and values.

Count matching rows within each group

To count qualifying records by category, filter first and then use groupby(...).size():

mask = df["score"].ge(80)
counts = df.loc[mask].groupby("department").size()

size() counts rows in each group, including rows whose other columns contain missing values. This makes it the appropriate choice when the question is how many records are in each group.

Rank #4
Sale
Pandas Journal (Diary, Notebook)
  • Crisp writing pages are perfect for personal reflections, sketching, or for recording favorite quotations or poems.
  • Premium 120 gsm paper takes pen or pencil beautifully.
  • Paper is acid free and of archival quality.
  • Light gray lines subtly guide your writing.
  • An inside back cover pocket expands to hold notes, cards, mementos, and more.

Choose the right counting method

Question Use What it counts
How many rows match a condition? int(mask.sum()), len(df.loc[mask]), or df.loc[mask].shape[0] Rows selected by the Boolean mask.
How many non-missing values are in each column? df.count() Non-NA cells in each column, not total rows. It excludes None, NaN, NaT, and pandas.NA. See the DataFrame.count documentation.
How many non-missing values are in each row? df.count(axis="columns") Non-NA cells per row.
How many rows are in each group? df.groupby("category").size() Rows per group, regardless of missing values in other columns.
How many non-missing values per group and column? df.groupby("category").count() Non-NA values in each column, separately for each group.
How often does each value in one column appear? df["category"].value_counts() Frequency of each value; set dropna to control how missing values are handled.
How often does each distinct combination of columns appear? df.value_counts(subset=["a", "b"], dropna=False) Frequency of unique row combinations. By default, combinations containing NA are omitted.

For SQL-style group record counts, pandas’ comparison with SQL uses groupby("sex").size() and explains why count() gives a different result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle missing values and empty results

A comparison involving a missing value does not make that row a true match. If missingness is the condition you want to count, test for it explicitly:

Best Value
Pandas Funny GIS/Programming/Python T-Shirt, Men, Black, Small
  • Funny design. Import pandas as pd, an all too familiar python code.
  • Featuring a familiar python code, this will get a laugh from all the nearby programmers and GIS professionals.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
mask = df["col"].isna()
count = int(mask.sum())

Use df.shape[0] when you need the DataFrame’s total row count regardless of missing entries. Unlike DataFrame.count(), it does not count non-missing cells.

For frequency counts, check the missing-value defaults: DataFrame.value_counts() omits combinations containing NA unless you pass dropna=False, while a column’s Series.value_counts() also has a dropna option. See the DataFrame.value_counts documentation and Series.value_counts documentation.

If you are summing numeric data rather than a Boolean mask, an empty or all-NA Series sums to zero by default. Set min_count=1 when you want an empty or all-NA input to produce NA instead of zero; the Series.sum documentation describes this behavior.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The linked API pages are from the pandas 3.0.6 documentation surfaced for this topic. If your project depends on version-specific behavior, consult the documentation for its installed pandas version.

Quick Recap

SaleBestseller No. 4
Pandas Journal (Diary, Notebook)
Pandas Journal (Diary, Notebook)
Premium 120 gsm paper takes pen or pencil beautifully.; Paper is acid free and of archival quality.
$10.99
Bestseller No. 5
Pandas Funny GIS/Programming/Python T-Shirt, Men, Black, Small
Pandas Funny GIS/Programming/Python T-Shirt, Men, Black, Small
Funny design. Import pandas as pd, an all too familiar python code.; Lightweight, Classic fit, Double-needle sleeve and bottom hem
$19.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.