Data Analyst Interview
Menu
Browse in your language. All mock interviews, preparation sessions and feedback are in English only.

Pandas size, count and nunique: Which Customer Count Is Correct?

Pandas · Customer metrics

Pandas size, count and nunique: Which Customer Count Is Correct?

Separate order rows, identified activity and distinct customer IDs.

Quick answer: pandas nunique counts distinct values, excluding missing values by default. It does not count orders, and including missing values does not identify the customers behind them. Use size for rows, count for nonmissing IDs, and nunique for distinct known IDs; report unidentified activity separately.

By Prakhar Shrivastava · October 23, 2026

Why six orders do not mean six customers

This fictional order extract contains three US orders, two UK orders and one German order. Customer A placed two US orders. Customer B placed one UK order, and customer C placed one German order. Two other orders have no customer identifier. All amounts are already normalized to USD, and each row represents one distinct order received for the same reporting period.

The known IDs are globally consistent in this exercise: A, B and C each refer to one customer across all feeds. Real systems need a documented identity rule before treating IDs from separate source systems as comparable.

Run three counts side by side

import pandas as pd
orders = pd.DataFrame({
    'market': ['US','US','US','UK','UK','DE'],
    'customer_id': pd.Series(['A','A',None,'B',None,'C'], dtype='string'),
    'amount_usd': [100,50,30,80,20,60]
})
report = orders.groupby('market')['customer_id'].agg(
    order_rows='size', identified_orders='count', known_customers='nunique')
report['unidentified_orders'] = report['order_rows'] - report['identified_orders']
print(report.to_string())
print('Known customers:', orders['customer_id'].nunique())
print('Values including missing:', orders['customer_id'].nunique(dropna=False))
        order_rows  identified_orders  known_customers  unidentified_orders
market                                                                     
DE               1                  1                1                    0
UK               2                  1                1                    1
US               3                  2                1                    1
Known customers: 3
Values including missing: 4

For the US, size returns three order rows, count returns two rows with a customer ID, and nunique returns one distinct known customer. The second order from A increases order volume without increasing the known-customer count. Germany has one row, one identified order and one known customer.

Does dropna=False recover unidentified customers?

No. In this explicitly typed string Series, nunique(dropna=False) returns four: A, B, C and a missing-value category. It does not mean that the two unidentified orders belong to a single fourth customer. They could belong to known customers, one new customer or two different new customers. The missing category cannot resolve that ambiguity.

Keep the result labeled as “distinct values including missing” if you use it for data profiling. For a customer report, publish three known customer IDs alongside two unidentified orders. Do not relabel four as the true customer count.

What can the revenue report still say?

The six known order amounts total $340. This reconciles order revenue without resolving customer identity. Revenue attached to missing IDs is $30 + $20 = $50. A correct revenue total does not establish a complete customer count, and it cannot justify assigning those dollars to a guessed customer.

For example, dividing $340 by three known customers includes unidentified revenue in the numerator while excluding unidentified customers from the denominator. Define whether a customer-level metric covers only identified orders before calculating it. Reconcile the excluded order count and amount so the narrower population is visible.

Can you sum distinct customers across markets?

Only if the market populations are disjoint under the chosen identity rule. This fixture has A only in the US, B only in the UK and C only in Germany, so the regional counts happen to add to three. If A also orders in the UK, summing the regional distinct counts counts A twice. Compute the overall nunique on the complete eligible ID column when IDs are globally consistent.

If regional systems reuse local customer IDs for different people, resolve the source-system identity before deduplicating. Adding market to the key is justified only when that combination actually represents the business identity. A traveler making purchases in two markets is not necessarily two customers.

What should you validate before using these counts?

Verify one row per order, eligible statuses, complete reporting dates, and the ID namespace. Blank strings and placeholder strings such as “unknown” are ordinary values unless your import and validation rules classify them as missing. Preserve raw identifiers and apply only documented normalization; arbitrary case conversion can merge distinct IDs.

This code assumes all market labels are present. Missing group keys require a separate grouping policy. The example also uses pandas string dtype explicitly so the missing representation is reproducible. Test your actual dtype and pandas version when adapting it.

Verification and further reading

Five assertions passed in pandas 2.2.3: the US count breakdown, three known IDs, four values including missing, two unidentified orders and $340 in order revenue. These are synthetic data checks, not measured site users or a claim about real customers.

Read the official nunique reference and count reference. Related exercises cover missing customer IDs in SQL, missing group keys, and why daily distinct users cannot simply be added.

Leave a Comment

Discover more from Data Analyst Interview

Subscribe now to keep reading and get access to the full archive.

Continue reading

✉ WhatsApp