Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Polars · Module

.diff

Calculates discrete differences between expression values and values shifted by a specified number of positions. It can preserve or drop null results.

How it works

Expr.diff compares each value with the value a configurable number of positions earlier. It returns null for positions without a prior comparison; setting null_behavior to drop removes those null results instead of preserving them.

Syntax

Expr.diff(*n: int | IntoExpr = 1*, *null_behavior: NullBehavior = 'ignore'*) → Expr

Parameters

NameTypeDescription
nint | IntoExprNumber of slots to shift.
null_behaviorNullBehaviorHow to handle null values; supported values are ignore and drop.

Returns

Expr

Key points

  • The expression computes differences between values and shifted values.
  • The shift distance defaults to one position and may be provided as an integer or expression.
  • Null handling defaults to ignore.
  • Use it inside with_columns to add a derived difference column.

Common mistakes

  • Only the supported null policies are ignore and drop; choose explicitly when null handling affects result length.
  • The n value controls the comparison distance, so larger values produce more leading unavailable results.

Example: Compute shifted differences

import polars as pl

df = pl.DataFrame({"value": [20, 10, 30, 25, 35]})
result = df.select(
    pl.col("value").diff(n=2, null_behavior="drop").alias("change")
)
print(result)

Computes two-step differences and removes the leading null results.

When to use it

Change analysis

Create period-over-period changes in a numeric column.

Lagged comparisons

Compare values with observations several rows earlier.

Feature engineering

Build derived columns in a DataFrame transformation.

Interview questions

QWhat does Expr.diff compute?

Expr.diff calculates the discrete difference between shifted expression values. With the default n=1, each result compares the current value with the preceding value, producing a leading null where no predecessor exists.

Follow-up: How can the output omit unavailable leading results? Use null_behavior="drop", which returns only the computed differences.

QWhat is the purpose of the n parameter?

n specifies how many positions to shift when calculating the difference. For example, n=2 compares each value with the value two positions earlier.

Follow-up: What happens near the beginning with n=2? Positions lacking a value two slots earlier produce null unless dropped.

QHow does null_behavior affect results?

null_behavior accepts ignore or drop. The choice determines how null values are handled and whether null results remain in the output.

Follow-up: Which option preserves the original result shape? ignore preserves the null results, while drop removes them.

  • polars.Series.diff
  • polars.Expr.list.diff
  • polars.Expr.shift

Source: polars.Expr.diff — Polars documentation. Checked 2026-10-15.