class nvtabular.ops.DifferenceLag(partition_cols, shift=1)[source]

Bases: nvtabular.ops.operator.Operator

Calculates the difference between two consecutive rows of the dataset. For instance, this operator can calculate the time since a user last had another interaction.

This requires a dataset partitioned by one set of columns (userid) and sorted further by another set (userid, timestamp). The dataset must already be partitioned and sorted before being passed to the workflow. This can be easily done using dask-cudf:

# get a nvt dataset and convert to a dask dataframe
ddf = nvtabular.Dataset(PATHS).to_ddf()

# partition the dask dataframe by userid, then sort by userid/timestamp
ddf = ddf.shuffle("userid").sort_values(["userid", "timestamp"])

# create a new nvtabular dataset on the partitioned/sorted values
dataset = nvtabular.Dataset(ddf)

Once passed an appropriate dataset, this operator can be used to create a workflow to compute the lagged difference within a partition:

# compute the delta in timestamp for each users session
diff_features = ["quantity"] >> ops.DifferenceLag(partition_cols=["userid"], shift=[1, -1])
processor = nvtabular.Workflow(diff_features)
  • partition_cols (str or list of str) – Column or Columns that are used to partition the data.

  • shift (int, default 1) – The number of rows to look backwards when computing the difference lag. Negative values indicate the number of rows to look forwards, making this compute the lead instead of lag.

transform(col_selector: nvtabular.columns.selector.ColumnSelector, df: pandas.core.frame.DataFrame)pandas.core.frame.DataFrame[source]

Transform the dataframe by applying this operator to the set of input columns

  • columns (list of str or list of list of str) – The columns to apply this operator to

  • df (Dataframe) – A pandas or cudf dataframe that this operator will work on


Returns a transformed dataframe for this operator

Return type


output_column_names(col_selector: nvtabular.columns.selector.ColumnSelector)nvtabular.columns.selector.ColumnSelector[source]