ML Foundations

Make a NumPy lag without circular wraparound

Build a one-step lag and validity mask without treating the last observation as the first predecessor.

Example results for Make a NumPy lag without circular wraparound. rolled: 40, 10, 20, 30
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

The first predecessor is missing

A one-step lag pairs each observation with the previous observation. Applying NumPy roll with a positive shift seems convenient, but roll wraps values that pass the end back to the beginning. For a chronological series this makes the last value appear as the first value’s predecessor. [1]

That circular predecessor may be correct for periodic data, but it is not an observed previous time step in a linear sequence. Decide how to represent the missing first predecessor before using the result.

References: [1]

Copy only the overlapping slices

Run python examples/numpy_roll_lag_without_wrap.py. The example compares roll with a separate lag array. Assigning values[:-1] to lag[1:] fills only positions that have a previous value; NumPy slicing and assignment describe the overlapping ranges. [2]

A Boolean mask marks those positions valid. The zero at the first lag position is only a storage placeholder, not an observed predecessor. The example selects current and previous values with the same mask and checks the expected pairs. [2]

Executed with Python 3.12.14; stdout and checksum recorded in private evidence.

import numpy as np

values = np.array([10, 20, 30, 40])
rolled = np.roll(values, 1)
lag = np.zeros_like(values)
valid = np.zeros(values.shape, dtype=bool)
lag[1:] = values[:-1]
valid[1:] = True

assert rolled.tolist() == [40, 10, 20, 30]
assert lag[valid].tolist() == [10, 20, 30]
assert values[valid].tolist() == [20, 30, 40]
print("rolled:", rolled.tolist())
print("lag storage:", lag.tolist())
print("valid:", valid.tolist())
print("valid current:", values[valid].tolist())
print("valid previous:", lag[valid].tolist())

Recorded output

rolled: [40, 10, 20, 30]
lag storage: [0, 10, 20, 30]
valid: [False, True, True, True]
valid current: [20, 30, 40]
valid previous: [10, 20, 30]

References: [1], [2]

Apply the boundary at the right scope

This fixture is one nonempty one-dimensional sequence and a one-position lag. For separate sequences, construct the mask independently at every sequence boundary; otherwise a value from another series can become a false predecessor.

For higher-dimensional data choose the time axis explicitly and align slices and masks with that axis. Roll flattens its input when no axis is supplied, so the default can also cross rows. This example does not implement arbitrary shifts, missing-value imputation or time-based train/test splitting. [1, 2]

References: [1], [2]

Sources

  1. NumPy roll
  2. NumPy indexing