Sub topic 6
Shifting by position versus shifting the index with freq
This chapter assumes you can create a Series with a DatetimeIndex, you know pd.date_range, and you have already used shift(1) to build a lag. Here you will learn the second way shift() works, the freq argument, and when to use it instead of a positional shift.
Two operations behind one method
shift() does one of two different things depending on whether you pass freq.
- Without
freq, pandas moves the values along the rows and leaves the index alone. This is a shift by position. Row 3 gets what was in row 2, and one end is filled withNaN. - With
freq, pandas moves the index labels by a time offset and leaves the values attached to their rows. This is a shift by label. Nothing is lost or created, so noNaNappears.
Both are called "shifting", and both can be described as "one day back". They give different results as soon as the index is not a perfectly regular sequence.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
by_position = s.shift(1)
by_label = s.shift(1, freq="D")
print(by_position)
print(by_label)by_position keeps the dates 2024-01-01 to 2024-01-04 and holds NaN, 10, 12, 15. Because NaN enters the column, the dtype becomes float64.
by_label has the dates 2024-01-02 to 2024-01-05 and holds 10, 12, 15, 11. The values are the same as the original, and the dtype stays int64. The first date has moved forward a day, and a new date, 2024-01-05, appears at the end.
What shifting the index does to the result
The label shift changes which dates the series covers. The first observation, made on January 1, is now labeled January 2. Read the result as "the value known one day earlier, filed under today's date".
This matters most when you combine the shifted series with another series. pandas aligns arithmetic on index labels, not on positions, so the shifted index lines up exactly with the original dates.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
change_pos = s - s.shift(1)
change_label = s - s.shift(1, freq="D")
print(change_pos)
print(change_label)change_pos has four rows: NaN, 2, 3, -4. change_label has five rows, from 2024-01-01 to 2024-01-05. Its values are NaN, 2, 3, -4, NaN.
The label version has NaN at both ends. January 1 has no earlier day to subtract. January 5 exists only in the shifted series, so there is nothing to subtract from. The middle three values are identical to the positional version.
If you want the original dates back, call .reindex(s.index) on the shifted series before doing arithmetic, or call .dropna() on the result. The reindex version is usually cleaner because the result has the same index as the input.
Where the two approaches disagree: gaps in the index
On a perfectly regular index, s.shift(1) and s.shift(1, freq="D") followed by .reindex(s.index) give the same numbers. The difference shows up when timestamps are missing. A positional shift counts rows, so a missing day silently changes what "one step back" means.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
irregular = s.drop(pd.Timestamp("2024-01-03"))
positional = irregular.shift(1)
calendar = irregular.shift(1, freq="D").reindex(irregular.index)
print(pd.DataFrame({
"sales": irregular,
"positional": positional,
"calendar": calendar,
}))The output is:
sales positional calendar
2024-01-01 10 NaN NaN
2024-01-02 12 10.0 10.0
2024-01-04 11 12.0 NaNOn January 4, the positional lag reports 12, which was recorded on January 2. That is two days back, not one. The calendar lag reports NaN, which is correct: there is no observation for January 3.
The calendar version makes the missing data visible instead of hiding it behind a wrong number. If you want to keep rows but treat gaps as missing, this pattern is a good default. The alternative is to insert the missing dates first with asfreq("D"), then use a positional shift. That is covered in the chapter on regularizing timestamps. Both approaches give a lag that means one calendar day.
Choosing between them
| Situation | Use | Why |
|---|---|---|
| Index is regular and complete | `shift(n)` | Simple, fast, and the index is unchanged. |
| Index has gaps and a lag must mean "n calendar units back" | `shift(n, freq=...)` then `reindex`, or `asfreq` then `shift(n)` | Row counts no longer equal elapsed time. |
| You want to move the dates themselves, for example to align a forecast with the date it applies to | `shift(n, freq=...)` | Values stay attached to their original rows. |
| Index is not a time index | `shift(n)` | `freq` needs a `DatetimeIndex`, `PeriodIndex` or `TimedeltaIndex`. |
Offsets beyond "D"
freq accepts any pandas offset alias, so the unit of the shift is not limited to days. The number of periods multiplies the offset: shift(2, freq="D") and shift(1, freq="2D") give the same result.
Calendar-aware offsets are the main reason to prefer freq over arithmetic on row counts. A business-day offset skips weekends.
import pandas as pd
prices = pd.Series(
[1, 2, 3, 4, 5],
index=pd.bdate_range("2024-01-03", periods=5),
name="price",
)
print(prices.index.day_name().tolist())
print(prices.shift(1, freq="B"))
print(prices.shift(1, freq="D"))The index runs Wednesday, Thursday, Friday, Monday, Tuesday. With freq="B", Friday's value moves to Monday, so the new labels are January 4, 5, 8, 9 and 10. With freq="D", Friday's value lands on Saturday, January 6, a date that is not a trading day. A series labeled with weekend dates will not align with your original business-day index, and joining the two produces unexpected NaN values.
Match the offset to the kind of calendar your data lives on. Business-day data uses "B", and weekly or monthly data uses the corresponding weekly or monthly aliases.
Lags measured in weeks
A seven-day lag is a common use for freq. Because it is defined in calendar time, it stays correct even if some days are missing.
import pandas as pd
daily = pd.Series(
range(14),
index=pd.date_range("2024-01-01", periods=14, freq="D"),
name="visits",
)
last_week = daily.shift(7, freq="D").reindex(daily.index)
week_over_week = daily - last_week
print(week_over_week.head(9))The first seven rows are NaN because there is no data from the week before. From January 8 onward the value is 7.0, since each day is seven higher than the same weekday a week earlier. If you removed a few days from daily, the seven-day lag would still compare each date with the date exactly one week before it, and would give NaN where that date is missing.
Rules and edge cases
fill_valueandfreqdo not combine. A label shift creates no missing values, so there is nothing to fill. Depending on your pandas version, passing both is ignored or raises aValueError. Choose one.freqneeds a time-like index. On a plainRangeIndex,shift(1, freq="D")raises an error, because there is no calendar to move along.- The index may grow. A shifted series covers new dates at one end and loses coverage at the other. Reindex to the original index if you need the original dates.
- Duplicate labels can appear. If you shift a daily index by a monthly offset, several days land on the same month boundary. Pandas does not stop you, and the result has repeated labels, which breaks alignment. Shift by an offset that matches the spacing of your data.
- Negative
periodswork too.shift(-1, freq="D")moves labels backward, so each value is filed under the previous day. Combined with arithmetic, this produces leads. Be careful, because a lead on the same row as a target can leak future information into a model. - DataFrames shift every column together.
df.shift(1, freq="D")moves the shared index for all columns, which keeps rows consistent. You can also shift the index alone withdf.index.shift(1, freq="D"), which returns a new index and leaves the data untouched.
Common mistakes
- Using
freqand expectingNaN. A label shift never producesNaNon its own. If your result has no missing values at the edges, that is why. The result also covers a different range of dates. - Forgetting to realign. Assigning
s.shift(1, freq="D")to a new column of a DataFrame with the original index pulls values by label. Dates that do not exist in the shifted index getNaN, and the last shifted date is dropped. This is correct, but it surprises people who expected the new column to hold the same number of valid values as before. - Picking the wrong offset. Shifting business-day data by
"D"places values on weekends, as shown above. - Mixing the two in one expression. Writing
s - s.shift(1, freq="D")ands - s.shift(1)in the same notebook and comparing results can look like a bug. They agree only when the index is regular, and the first has an extra row.
Summary of the working model
A positional shift answers "what was the previous row?". A label shift answers "what was recorded one unit of time earlier?". On complete, evenly spaced data, they match. When the index has gaps, only the label version, followed by reindex, gives a lag that means what the column name says.
Exercise
A daily series has the index 2024-03-01, 2024-03-02, 2024-03-04, 2024-03-05 (March 3 is missing) and the values 5, 6, 8, 9. For each date, what do s.shift(1) and s.shift(1, freq="D").reindex(s.index) return?
Show answer
s.shift(1) returns NaN, 5, 6, 8 for the four dates. The value 6 on March 4 comes from March 2, two days earlier. s.shift(1, freq="D").reindex(s.index) returns NaN, 5, NaN, 9. March 4 is NaN because there is no observation on March 3, and March 5 gets 8 from March 4.
Exercise
You have a business-day price series indexed with pd.bdate_range. You write prices.shift(1, freq="D") and join it to the original series. Why do Mondays end up with missing values in the joined data, and what should you change?
Show answer
Shifting by one calendar day moves Friday's value to Saturday, a date that is not in the business-day index, so the Monday row has no matching shifted label. Use freq="B" so that Friday's value moves to Monday, or use the positional prices.shift(1) if the index is complete and every row is one trading day.
Exercise
What happens if you call s.shift(1, freq="D", fill_value=0), and why?
Show answer
Depending on the pandas version, the fillvalue is ignored or a ValueError is raised. A label shift moves the index and creates no NaN values, so there is nothing to fill. Use fillvalue only with a positional shift.