Sub topic 4
Why NaN appears and how to fill it
This chapter assumes you can build a Series with pd.date_range, index it by date, and call shift(1) on it. You should also know the basic NaN tools: isna(), fillna() and dropna(). The chapter explains where the missing values from shift() come from, what they do to your data types, and how to handle them without distorting later calculations.
Where the NaN values come from
shift() slides the values along the index and leaves the index in place. The result has the same length and the same dates as the input. A shift by one row moves every value one slot down, so the last value has no slot left and is dropped. The first slot has nothing to hold, so pandas fills it with a missing value.
Here is the series used throughout this chapter.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
lag1 = s.shift(1)
print(lag1)The output is:
2024-01-01 NaN
2024-01-02 10.0
2024-01-03 12.0
2024-01-04 15.0
Freq: D, Name: sales, dtype: float64On 2024-01-01 there is no earlier day in the data, so the lag is unknown. The value 11 from 2024-01-04 has moved past the end and is gone.
The number of edge NaN values equals the absolute value of periods. Shifting by 2 gives two NaN rows. A positive shift puts them at the start, and a negative shift (a lead, from the previous chapter) puts them at the end.
print(s.shift(2).isna().sum()) # 2
print(s.shift(-3).isna().sum()) # 3
print(s.shift(4).isna().all()) # TrueIf abs(periods) is greater than or equal to the length of the series, every value is NaN. No error is raised. This is a common silent failure when you shift a short group or a small test sample by a long lag such as 7 or 30.
The dtype side effect
The integer sales column became float64 after the shift. NumPy integer arrays cannot hold NaN, so pandas upcasts the whole result to float. Four problems follow from this:
- Values print as
10.0instead of10. - The column no longer matches the original dtype, which matters if you compare or merge on it.
- Very large integers (above 2**53) can lose precision as floats.
- Code that expects integers, such as indexing or
astypechecks, can fail.
You can check the dtype before and after:
print(s.dtype) # int64
print(s.shift(1).dtype) # float64Filling the edge with fill_value
fill_value replaces the empty slots created by the shift. Because no NaN is introduced, the integer dtype is kept.
filled = s.shift(1, fill_value=0)
print(filled)The output is:
2024-01-01 0
2024-01-02 10
2024-01-03 12
2024-01-04 15
Freq: D, Name: sales, dtype: int64fill_value only affects the slots that shift() creates. It does not touch NaN values that were already in your data. It is also not the same as calling fillna() afterward. s.shift(1).fillna(0) gives the same numbers, but the dtype stays float64 because the NaN existed briefly.
On a DataFrame, fill_value applies one value to every column.
df = pd.DataFrame(
{"sales": [10, 12, 15, 11], "visits": [100, 120, 90, 110]},
index=s.index,
)
print(df.shift(1, fill_value=0))If each column needs its own fill, shift first and then pass a dictionary to fillna(). Restore the integer dtypes afterward.
lagged = df.shift(1).fillna({"sales": 0, "visits": df["visits"].iloc[0]})
lagged = lagged.astype({"sales": "int64", "visits": "int64"})
print(lagged)
print(lagged.dtypes)Keeping integers with a nullable dtype
Pandas has nullable integer types that store missing values as pd.NA without converting to float. Convert the column to "Int64" (capital I) before shifting.
nullable = s.astype("Int64").shift(1)
print(nullable)
print(nullable.dtype) # Int64The first value prints as <NA> and the rest stay integers. This is useful when the missing value must stay distinguishable from a real zero and you still want integer semantics. Some libraries, especially older scikit-learn code paths, expect plain NumPy arrays and may convert Int64 columns to object. Check how your modeling library treats them before you rely on this.
Choosing a fill strategy
Filling is a modeling decision. The edge value is unknown, and any number you insert is a guess. The table compares the common options.
| Option | Code | Effect | Main risk |
|---|---|---|---|
| Leave as NaN | `s.shift(1)` | Honest about unknown data | Float dtype, and many models reject NaN |
| Constant | `s.shift(1, fill_value=0)` | Keeps dtype, simple | 0 can look like a real observation |
| Drop rows | `df.dropna(subset=["lag1"])` | Only fully known rows remain | Loses the first `n` rows per series |
| Backfill | `s.shift(1).bfill()` | Uses the next known lag | Copies a current value into the past (see below) |
| Nullable dtype | `s.astype("Int64").shift(1)` | Integers with `pd.NA` | Library support varies |
Constants can bias statistics
A fill value takes part in every later calculation. Filling with 0 pulls averages down.
print(s.shift(1).mean()) # 12.333333333333334
print(s.shift(1, fill_value=0).mean()) # 9.25The first mean ignores the missing edge, because pandas skips NaN by default. The second counts a day with zero sales that never happened. If 0 is a plausible real value, as in sales, a zero fill hides which rows were really missing. A sentinel such as -1 is easy to spot, but it is worse for averages and for distance-based models. In those cases it is usually better to keep NaN and drop or impute deliberately later.
Backfill can leak
s.shift(1).bfill() gives [10, 10, 12, 15]. The first row's "previous day" is 10, but 10 is that row's own value. A lag feature should only contain information available before the row's date. Backfilling copies the current value into the past. For one row this is a small effect, but the pattern grows into a real problem with larger lags and with leads. The last chapter on leakage covers this in detail. For now, prefer leaving the edge as NaN or dropping those rows.
Dropping the edge rows
When you need complete rows, drop the rows whose lag is unknown. Name the columns in subset so that other, legitimate missing values are handled separately.
frame = s.to_frame()
frame["lag1"] = s.shift(1)
frame["lag2"] = s.shift(2)
complete = frame.dropna(subset=["lag1", "lag2"])
print(complete)Only the rows from 2024-01-03 onward remain. The largest lag decides how many rows you lose, so a lag of 30 removes 30 rows from the start.
Edge NaN versus NaN that was already there
shift() moves existing NaN values along with everything else. A shifted series can therefore contain two kinds of missing values that look identical.
s2 = pd.Series(
[10, None, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
)
lag = s2.shift(1)
print(lag)The output has NaN on 2024-01-01 (the edge) and NaN on 2024-01-03 (the original gap, moved one slot). To count only the data-driven ones, skip the first n rows of the shifted result.
n = 1
print(lag.isna().sum()) # 2 in total
print(lag.iloc[n:].isna().sum()) # 1 that came from the dataThis slicing works for positive n. For a negative shift, the edge is at the end, so use lead.iloc[:len(lead) - n] with n = abs(periods).
When fillna() is applied after a shift, it fills both kinds. Use fill_value if you want only the edge filled and the real gaps left visible.
print(s2.shift(1, fill_value=0))The edge becomes 0 and the shifted gap on 2024-01-03 stays NaN.
A decision flow
Common mistakes
- Using
fillna(method="bfill")on a lag. It leaks the current value into the past, as shown above. - Filling with the series mean computed on all rows. The mean includes future observations, which is another form of lookahead.
- Forgetting the dtype change. A column that was
int64becomesfloat64and later joins or exports show10.0. - Shifting by more than the group length. Every value is
NaNand nothing warns you. Check withisna().all()while developing. - Treating 0 as "no data". If zero is a valid observation, a zero fill makes missing and real values indistinguishable.
Putting it together
This function builds a lag column, reports how many edge rows are unknown, and lets the caller choose between keeping, filling and dropping them.
import pandas as pd
def add_lag(series, periods=1, how="keep", fill_value=0):
"""Return a DataFrame with the series and its lag.
how: "keep" leaves NaN, "fill" uses fill_value, "drop" removes edge rows.
"""
name = f"lag{periods}"
out = series.to_frame()
if how == "fill":
out[name] = series.shift(periods, fill_value=fill_value)
else:
out[name] = series.shift(periods)
if how == "drop":
out = out.dropna(subset=[name])
return out
sales = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
print(add_lag(sales, 2, how="keep"))
print(add_lag(sales, 2, how="fill"))
print(add_lag(sales, 2, how="drop"))The keep result has two NaN rows and a float lag column. The fill result has two zeros and an integer lag column. The drop result has only the last two rows. Note that drop uses dropna on the lag column, so it would also remove rows where the data itself had a gap. If your series can contain real gaps, drop by position with out.iloc[periods:] instead.
Summary of the rules
shift(n)always producesabs(n)empty slots, and they areNaNunless you passfill_value.NaNforces integer columns tofloat64.fill_valueor a nullableInt64dtype avoids that.fill_valuetouches only the edge.fillna()touches every missing value.- Any constant you insert takes part in later means, sums and model fits, so choose it deliberately.
- Fill methods that look at neighboring rows, such as
bfill()or a full-sample mean, can pull in future information.
Exercise
Given s = pd.Series([3, 5, 8, 6, 9]) with a default integer index, what are the dtype and the mean of s.shift(2) and of s.shift(2, fill_value=0)? Explain the difference in both results.
Show answer
s.shift(2) has dtype float64 and its first two values are NaN. Its mean is (3 + 5 + 8) / 3 = 5.333..., because mean() skips NaN. s.shift(2, fill_value=0) keeps dtype int64 and has values [0, 0, 3, 5, 8]. Its mean is 16 / 5 = 3.2, because the two filled zeros are counted as observations and pull the average down.
Exercise
A DataFrame df has an integer column units with a DatetimeIndex. You need units_lag7, but the model rejects NaN and you cannot invent values. You also want to keep the integer dtype where possible. Write one approach and say what it costs.
Show answer
Shift, then drop the unknown rows by position: df["units_lag7"] = df["units"].shift(7) followed by df = df.iloc[7:].astype({"units_lag7": "int64"}). Dropping the first 7 rows leaves no NaN, so the cast back to int64 succeeds. The cost is losing the first 7 rows of data. Using dropna(subset=["units_lag7"]) would also work if units has no real gaps, but iloc[7:] removes only the edge rows.
Exercise
Why is s.shift(1).bfill() a poor way to remove the leading NaN of a lag feature?
Show answer
bfill() copies the next known lag backward into the first row. For shift(1), that value is the first row's own current value, so the feature for that date contains information from that same date instead of from the past. This is lookahead leakage, and it grows worse with larger lags.