← Back to Pandas Course | Chapter 10: Time Series | Lesson 5 of 7

shift/diff

shift moves values up or down and diff subtracts the previous value, both handy for change over time.

In this page:

  1. shift/diff
Syntax
python
df["column"].shift(1)
df["column"].diff()

shift/diff

shift(1) moves data down one row so each row can see the previous value. diff() is the difference from the prior row and pct_change() gives the percentage change. Negative shift values look forward.

Note: pct_change is diff divided by the previous value.

Example: shift/diff

python
import pandas as pd

s = pd.Series([100, 110, 99, 120])
print(s.shift(1).tolist())
print(s.diff().tolist())
print(s.pct_change().round(3).tolist())

# Output:
# [nan, 100.0, 110.0, 99.0]
# [nan, 10.0, -11.0, 21.0]
# [nan, 0.1, -0.1, 0.212]
Related Topics
Common Mistakes
  1. Forgetting the first row becomes NaN
  2. Shifting the wrong direction
  3. Using shift on unsorted data
Chapter Summary
  • shift moves values
  • diff gives change
  • pct_change gives relative change
  • The first row becomes NaN
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.