Time-series change analysis
Track period-over-period movement in numeric columns.
Pandas · Module
Returns the fractional change between current and prior DataFrame values. By default it compares adjacent rows; multiply the result by 100 to express the change as a percentage.
DataFrame.pct_change compares each value with the value a specified number of rows earlier and returns the relative change. With the default period of one, the first row has no predecessor and therefore produces a missing value; multiply the result by 100 to express percentages.
DataFrame.pct_change(*periods=1*, *fill_method=None*, *freq=None*, ***kwargs*)| Name | Type | Description |
|---|---|---|
periods | int, default 1 | Number of periods to shift when forming the relative change. |
fill_method | None | Must be None in the current stable API; missing-value filling is not performed by default. |
freq | DateOffset, timedelta, or str, optional | Optional time increment used by the time-series API. |
**kwargs | object | Additional keyword arguments passed to DataFrame.shift or Series.shift. |
Series or DataFrame — the same type as the calling object.
import pandas as pd
df = pd.DataFrame({"sales": [100, 120, 90]})
change = df.pct_change()
print(change)
print((change * 100).round(1))Computes row-to-row fractional changes and multiplies them by 100 when percentage values are needed.
Track period-over-period movement in numeric columns.
Normalize revenue, usage, or metric changes across differently scaled columns.
Compare observations separated by a fixed number of rows.
It calculates the fractional, relative change between the current value and a prior value. The default period is one, so each row is compared with the immediately preceding row; the returned object has the same type as the caller.
Follow-up: How would you calculate percentage points? Multiply the returned DataFrame by 100.
periods specifies how far back to look when forming the comparison. A value of two compares each row with the row two positions earlier, rather than with its immediate predecessor.
Follow-up: What happens to the first two rows for periods=2? They have no corresponding prior values and therefore yield missing results.
freq is an optional DateOffset, timedelta, or string used with the time-series API. Additional keyword arguments are passed to DataFrame.shift or Series.shift.
Follow-up: When would freq be useful? Use it when comparisons should follow a time-based increment, such as a month-end offset or business-day offset.
DataFrame.shiftSeries.shiftSeries.pct_changeDataFrameGroupBy.pct_change