Sub topic 4
Why NaN appears and how to fill it
This chapter assumes you can build a pandas Series with a DatetimeIndex and that you know what shift(1) does from the previous chapters. Here you will see why shifting creates NaN values, what that does to your data types, and when filling them is a good idea.
Where the NaN comes from
shift() moves values along the index but leaves the index in place. Nothing can move into the first row, so pandas puts a missing value there.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
print(s.shift(1))
print(s.shift(2))shift(1) produces one NaN at the start, and shift(2) produces two. In general, shift(n) creates abs(n) missing values. With a positive n they sit at the start. With a negative n they sit at the end.
| Call | Missing rows | Position |
|---|---|---|
| `s.shift(1)` | 1 | first row |
| `s.shift(3)` | 3 | first three rows |
| `s.shift(-1)` | 1 | last row |
| `s.shift(-2)` | 2 | last two rows |
The values pushed past the other end are dropped. The Series keeps its original length.
The dtype side effect
The original sales Series has dtype int64. NumPy integers cannot hold NaN, so pandas converts the shifted result to float64:
print(s.dtype)
print(s.shift(1).dtype)This prints int64, then float64. The values 10, 12, 15 become 10.0, 12.0, 15.0. This is harmless for most calculations. It matters when you export to a system that expects integers, or when you compare the shifted column to integer data.
Filling with fill_value
Pass fill_value to shift() to choose what goes into the new edge rows:
filled = s.shift(1, fill_value=0)
print(filled)
print(filled.dtype)The first row is now 0 instead of NaN. The dtype stays int64, because no missing value was introduced.
fill_value only fills the rows that the shift created. A NaN that was already in your data moves with its value and stays NaN:
t = pd.Series(
[1.0, None, 3.0],
index=pd.date_range("2024-01-01", periods=3, freq="D"),
)
print(t.shift(1, fill_value=0))The result is 0.0, 1.0, NaN. The edge was filled, and the original gap in the data was not. This is a useful property, because you can fill only the artificial edge and leave real gaps visible.
Other ways to deal with edge NaN
You have four common options, and each makes a different claim about your data.
- Leave the NaN. It honestly says "no previous value exists." Many pandas operations, such as
mean()andsum(), skip it by default. - Drop the rows with
dropna(). This is typical when building a training set, because rows without a lag cannot be used. - Fill with a constant using
fill_value. Choose a value that makes sense for the column. - Keep integers with a nullable type.
astype("Int64")(capital I) allows missing values without converting to float.
print(s.shift(1).dropna())
nullable = s.astype("Int64").shift(1)
print(nullable)
print(nullable.dtype)The dropna() result has three rows, starting on 2024-01-02. The nullable version shows <NA> in the first row and keeps the dtype Int64.
Common errors
- Filling with 0 when 0 is a real value. If
salescan be 0 on a quiet day, a lag filled with 0 looks like "yesterday had no sales." For the first date, nobody knows yesterday's sales. A constant is reasonable only when it is the true starting state, such as an opening balance of 0. - Using
fillna(method="ffill")orffill()on a lag. Forward fill copies the last known value into every gap. After a shift, it also hides real missing data inside the series, not only the edge. Preferfill_value, which touches only the new edge. - Using
bfill()on a lag. Backward fill pulls a later value into an earlier row. For a lag feature, this brings future information into the past and leaks it. The leakage chapter covers this in detail. - Forgetting the dtype change. If a later step expects integers,
astype, afill_value, or a nullable dtype will fix it. Callingastype(int)on a column that still hasNaNraises an error.
Choosing quickly
Ask what the first row's lag means in your problem. If it truly does not exist, keep NaN or drop the row. If a known starting value exists, such as zero inventory at launch, use fill_value. If you only need integers to survive, use Int64.
Exercise
Given s = pd.Series([5, 8, 6], index=pd.date_range("2024-02-01", periods=3, freq="D")), what are the values and dtype of s.shift(1, fill_value=0), and what are the values and dtype of s.shift(1)?
Show answer
s.shift(1, fill_value=0) gives 0, 5, 8 with dtype int64, because no NaN is introduced. s.shift(1) gives NaN, 5.0, 8.0 with dtype float64, because the NaN forces a float conversion.
Exercise
Why is s.shift(1).bfill() a poor way to remove the leading NaN from a lag feature?
Show answer
bfill() copies the next valid value backward into the NaN row. The first row would receive the second row's lag, which is the first row's own value, so the feature contains information that was not available at that time. Use fill_value with a known starting value, leave the NaN, or drop the row.