A conditional count is a common move in accounting: walk a list, and each time a
row meets a condition, add 1. You did it in Excel with COUNTIF. In Python, a loop does the
same thing, adding 1 when the test passes. Here they are side by side.
This is a short list of invoices. An invoice is overdue when days_overdue is greater than 0. Change the yellow days_overdue cells on the left, then Run the Python loop on the right and watch the two counts stay in step.
The overdue helper cell is 1 when days_overdue is greater than 0, else 0. The
count cell is =COUNTIF over the days_overdue column. Click a cell to see its
formula in the bar. The yellow cells are editable.
sum(1 for inv in invoices if inv["days_overdue"] > 0)
. In pandas, you build a boolean mask over the whole column and sum it:
(df["days_overdue"] > 0).sum(). True counts as 1, False as 0, so the sum is the count.
No loop to write, and it never misses a row.