In pandas, how do `groupby().size()`, `groupby().count()` and `groupby().nunique()` differ when the `amount` column has missing values?
answer
- rows versus non-missing cells
- one number per group or per column
- distinct values skip NaN by default
- as_index=False names a size column
basics
~20 ssize() counts every row in each group, missing values included, and returns one number per group. count() counts non-missing values per column, so a NaN amount lowers it. nunique() counts distinct non-missing values per column.
solid answer
~40 s`size()` is the group's row count: it never looks at values, returns a `Series` (or, with `as_index=False`, a `DataFrame` with a `size` column), and a NaN anywhere changes nothing. `count()` works per column and excludes missing values, so on a `DataFrameGroupBy` it returns a `DataFrame` with one count per non-key column: a customer with three orders, one of them with a missing `amount`, shows `size` 3 but an `amount` count of 2. `nunique()` counts distinct values per column and also skips missing values, because its `dropna=True` default; `dropna=False` counts NaN as one more value. Choose by the question: orders placed is `size`, orders with a recorded amount is `count`, distinct categories bought is `nunique`.
code
python · 15 linesimport numpy as np
import pandas as pd
orders = pd.DataFrame({
"customer_id": ["c1", "c2", "c1", "c3", "c2", "c1"],
"category": ["books", "toys", "books", "garden", "toys", "toys"],
"amount": [20.0, 35.0, np.nan, 50.0, 15.0, 10.0],
})
gb = orders.groupby("customer_id")
print(gb.agg(
orders=("amount", "size"),
paid=("amount", "count"),
categories=("category", "nunique"),
))go deeper
Recall that size counts rows and count counts non-missing values, and give an orders-per-customer example where they differ.
Explain the shapes: size gives one number per group, count and nunique one per column, and how as_index=False turns size into a frame with a size column.
Show you use size against count as a per-group missing-data audit before trusting averages, and pick nunique's dropna setting from what missing means in the data.
Push for reports that say which count they show, rows, recorded values or distinct values, so a dashboard figure never silently changes meaning when data quality shifts.
## Three counts, three different questions All three return one result row per group, but they answer different questions and return different shapes: | Method | Counts | Missing values | On a `DataFrameGroupBy` returns | |---|---|---|---| | `size()` | rows in the group | included; values are never inspected | a `Series`, one number per group | | `count()` | non-missing values | excluded | a `DataFrame`, one column per non-key column | | `nunique()` | distinct non-missing values | excluded by default (`dropna=True`) | a `DataFrame`, one column per non-key column | On a single selected column, `orders.groupby('customer_id')['amount']`, `count()` and `nunique()` return a `Series` too. ## `size()`: how many rows - `size()` depends only on how the rows were split. A row whose `amount` and `category` are both missing still counts. - With the default `as_index=True` it returns a `Series` indexed by the group keys, with no name. - With `as_index=False` it returns a `DataFrame` whose count sits in a column literally called `size`, next to the key columns. That is the quickest "orders per customer" table. - In named aggregation, `orders=('amount', 'size')` gives the same row count; the column named in the tuple does not matter to the result, because size ignores values. ## `count()`: how many recorded values - `count()` is computed column by column, and each column skips its own missing values. Two columns of the same group can therefore report different counts. - The grouping columns are excluded from the output, so `orders.groupby('customer_id').count()` reports every other column. - `count()` is the right tool when the question is about data quality or coverage: how many orders have a recorded amount, how many have a coupon code. - In named aggregation, `paid=('amount', 'count')` counts the recorded amounts only. ## `nunique()`: how many distinct values - `nunique()` counts **distinct** values per group, such as how many different categories a customer bought from. - Its `dropna` parameter defaults to `True`, so missing values are not counted as a value. With `dropna=False`, missing counts as one extra distinct value, which matters when "no coupon" is a meaningful state. - In named aggregation it is `('category', 'nunique')`. - This `dropna` belongs to `nunique` only; it is separate from the `dropna` argument of `groupby`, which decides whether rows with a missing **key** form a group at all. ## Reading a mismatch When `size()` and `count()` disagree for a group, the difference is exactly the number of missing values in that column for that group. That makes the pair a quick missing-data audit per group: 1. Compute `gb.size()` and `gb['amount'].count()`. 2. Subtract: the difference is the number of orders with a missing amount per customer. 3. Decide whether those rows should be filled, excluded, or reported, before any average is trusted. ## Reading the example In the code example below, customer `c1` has three orders: `books` for 20.0, `books` with a missing amount, and `toys` for 10.0. 1. `orders=('amount', 'size')` reports 3, because all three rows belong to the group. 2. `paid=('amount', 'count')` reports 2, because one amount is NaN. 3. `categories=('category', 'nunique')` reports 2, because `books` appears twice and counts once. Customer `c2` has two orders with recorded amounts, both in `toys`, so the counts are 2, 2 and 1. Each number answers a different business question about the same rows, which is why a report column labelled only "orders" invites misreading. All three are built-in groupby methods with efficient, groupby-specific implementations. Writing the same count as a callable, such as `('amount', len)` or a lambda, gives the same row count but calls Python once per group, which is slower on many groups for no benefit. ## Pitfalls - Using `count()` for "orders per customer" and undercounting every customer with a missing value in the chosen column. - Treating `count()` on the whole frame as one number per group, when it returns one per column. - Expecting `size()` to return a `DataFrame` with a named column by default; it does so only with `as_index=False`. - Confusing `len(gb)`, which is the number of groups, with `size()`, which is the number of rows in each group. - Expecting `nunique()` to count missing as a category without passing `dropna=False`. - Reaching for `value_counts` when the question is a single count per group; counting values outside a groupby is covered with duplicates and counting.
- How do you get order counts as a column beside `customer_id`?`orders.groupby('customer_id', as_index=False).size()` returns a `DataFrame` with `customer_id` and a column named `size`. To choose the name, use named aggregation: `orders.groupby('customer_id', as_index=False).agg(orders=('amount', 'size'))`.
- When would you pass `dropna=False` to `nunique()`?When a missing value is itself a meaningful state that should count as one distinct value, for example counting the distinct coupon codes per customer where 'no coupon' should be one of them. With the default `dropna=True`, missing values are not counted at all.
- How does `len(orders.groupby('customer_id'))` differ from `size()`?`len` of the groupby object, like its `ngroups` attribute, is the number of groups: one number for the whole split. `size()` returns the number of rows in each group, one number per group, and its values add up to the rows that were grouped.
- size() and count() always return the same numbers.
- count() includes rows whose value is NaN.
- size() returns one count per column, like count().
- nunique() counts NaN as a distinct value by default.
- len() of a groupby object gives the rows in each group.