Sub topic 9
Empty bins: NaN, zero, and min_count
This chapter assumes you can build a DatetimeIndex, call resample() with a frequency string such as "MS", and apply an aggregation like sum() or mean(). Here you will see what pandas returns for a bin that contains no rows, why the answer differs between aggregations, and how to control it.
What an empty bin is
resample() builds a regular grid of bins from the first timestamp to the last one in your data. If the data has a gap, some bins in that grid contain no rows. Those are empty bins. pandas still returns a row for each of them, so the output index stays regular.
Two limits apply:
- Bins exist only between the first and last observation. pandas does not add empty bins before the first row or after the last.
- A bin that has rows whose values are all
NaNis not empty, but it behaves much like an empty one. That case comes up later in the chapter.
The default result depends on the aggregation
An empty bin does not always come out as NaN. Each aggregation has its own result for "nothing to aggregate".
import pandas as pd
df = pd.DataFrame(
{
"date": pd.to_datetime(["2024-01-05", "2024-01-20", "2024-03-02"]),
"sales": [100, 150, 80],
}
)
r = df.resample("MS", on="date")["sales"]
print(r.sum())
print(r.mean())
print(r.count())February has no rows. The three results are:
date
2024-01-01 250
2024-02-01 0
2024-03-01 80
Freq: MS, Name: sales, dtype: int64
date
2024-01-01 125.0
2024-02-01 NaN
2024-03-01 80.0
Freq: MS, Name: sales, dtype: float64
date
2024-01-01 2
2024-02-01 0
2024-03-01 1
Freq: MS, Name: sales, dtype: int64The sum is 0 and the mean is NaN. Both follow from the math of an empty collection. The sum of nothing is zero, and the mean of nothing is undefined.
| Aggregation | Result for an empty bin |
|---|---|
| `sum()` | `0` |
| `prod()` | `1` |
| `count()` | `0` |
| `size()` | `0` |
| `nunique()` | `0` |
| `mean()`, `median()`, `std()`, `var()` | `NaN` |
| `min()`, `max()` | `NaN` |
| `first()`, `last()` | `NaN` |
| `ohlc()` | `NaN` in all four columns |
Zero and NaN carry different meanings
The default 0 from sum() can mislead you. In the example above, February's 0 looks like a month with no sales. It might instead be a month where the data was never collected. pandas cannot tell these cases apart, so you decide which reading is correct.
- Use
0when absence means "none happened". Event counts, units sold, and error counts are examples. - Use
NaNwhen absence means "unknown". Sensor readings, prices, and temperatures are examples.
A sum is often used as a total for data of the second kind, such as rainfall from a gauge that can go offline. Showing 0 for an offline month is a silent error.
Getting NaN from sum with min_count
sum() and prod() accept a min_count argument. It is the minimum number of valid (non-NaN) values a bin needs. If a bin has fewer, the result is NaN.
import pandas as pd
df = pd.DataFrame(
{
"date": pd.to_datetime(["2024-01-05", "2024-01-20", "2024-03-02"]),
"sales": [100, 150, 80],
}
)
sparse = df.resample("MS", on="date")["sales"].sum(min_count=1)
print(sparse)date
2024-01-01 250.0
2024-02-01 NaN
2024-03-01 80.0
Freq: MS, Name: sales, dtype: float64Two things changed. February is now NaN, and the dtype became float64, because integers cannot hold NaN. Expect this dtype change whenever a bin can come out missing.
The default is min_count=0, which is why an empty sum is 0. Setting min_count=1 means "at least one real value or the result is missing". You can use a higher number to require more evidence, for example min_count=7 so a weekly total is reported only when all seven daily readings are present.
Bins whose values are all NaN
A bin is not empty if it has rows, even when every value in those rows is NaN. sum() skips NaN values by default, so it sees nothing to add and returns 0, the same as for an empty bin.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=6, freq="D")
s = pd.Series([1.0, 2.0, float("nan"), float("nan"), 5.0, 6.0], index=idx)
print(s.resample("2D").sum())
print(s.resample("2D").sum(min_count=1))2024-01-01 3.0
2024-01-03 0.0
2024-01-05 11.0
Freq: 2D, dtype: float64
2024-01-01 3.0
2024-01-03 NaN
2024-01-05 11.0
Freq: 2D, dtype: float64The middle bin holds two rows, both NaN. With the default it reports 0.0. With min_count=1 it reports NaN. So min_count handles both causes of missing data: absent rows and rows with no valid values.
Telling the two situations apart
Sometimes you need to know which bins lacked data, or why. Two counting methods help:
size()counts rows in each bin, including rows withNaN.count()counts only non-NaN values.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=6, freq="D")
s = pd.Series([1.0, 2.0, float("nan"), float("nan"), 5.0, 6.0], index=idx)
s = s.drop(pd.Timestamp("2024-01-06"))
r = s.resample("2D")
report = pd.DataFrame({"rows": r.size(), "valid": r.count(), "total": r.sum(min_count=1)})
print(report) rows valid total
2024-01-01 2 2 3.0
2024-01-03 2 0 NaN
2024-01-05 1 1 5.0A bin with rows equal to 0 has no rows. A bin with rows above 0 and valid equal to 0 has rows that are all NaN. A bin where valid is smaller than rows is partial, and its total covers fewer points than the bin suggests. A report like this is a cheap data-quality check before you trust a monthly figure.
Handling empty bins after the fact
Once the result exists, you have several options.
- Leave the
NaNvalues in place. Plots draw a gap, and later arithmetic propagates the missing value instead of hiding it. - Drop the empty bins with
.dropna(). The index is then no longer regular, so use this for display or export, not for further resampling or alignment. - Replace
NaNwith a number using.fillna(0). This is the explicit version of the defaultsum()behavior. - Carry values forward with
.ffill(). This suits state-like data, such as the last known price in an empty day.
For the last option, pick the aggregation first and fill afterward:
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-05"])
price = pd.Series([10.0, 11.0, 14.0], index=idx)
daily = price.resample("D").last().ffill()
print(daily)2024-01-01 10.0
2024-01-02 11.0
2024-01-03 11.0
2024-01-04 11.0
2024-01-05 14.0
Freq: D, dtype: float64The last() call produces NaN for January 3 and 4, and ffill() replaces them with the last known price.
Mixed columns in one call
When you aggregate several columns with a dict, each column follows its own rule for empty bins. In a table with price averaged and volume summed, an empty month shows NaN for price and 0 for volume. That combination is usually correct, since no trades means no price but a volume of zero. If you want volume missing too, use a separate sum(min_count=1) call on that column and join the results.
Summary of decisions
- Check whether absence means "none" or "unknown" before you choose an aggregation.
- Use
sum(min_count=1)when a total of nothing should be missing. - Use
size()andcount()to see how many rows and valid values each bin held. - Expect
float64output whenNaNis possible. - Fill after aggregating, and choose the fill method to match the meaning of the data.
Exercise
A daily series of rainfall readings has no rows for the week of 2024-02-12, because the gauge was offline. You compute s.resample("W").sum(). What does the offline week show, and what change makes it show NaN instead? What would still be different if the gauge had instead logged the week as rows of NaN?
Show answer
The offline week shows 0.0, because sum() of an empty bin is 0. Calling s.resample("W").sum(min_count=1) makes it NaN. If the gauge had logged rows of NaN, the bin would not be empty, but the default sum() would still return 0 because it skips NaN values. min_count=1 would give NaN in that case as well, and size() would show a nonzero row count while count() would show 0.