shift(1) moves every value down by one position, introducing NaN at the top since there's no longer a value to fill the first row, while leaving the index unchanged — this makes subtracting a shifted column from the original a standard, concise way to compute the difference between each row and the one before it, like day-over-day change. A negative periods argument shifts values upward instead, which is useful for comparing each row against a future one, like computing next-day changes.
1Understanding df.shift()
shift(1) moves every value down by one position, introducing NaN at the top since there's no longer a value to fill the first row, while leaving the index unchanged — this makes subtracting a shifted column from the original a standard, concise way to compute the difference between each row and the one before it, like day-over-day change. A negative periods argument shifts values upward instead, which is useful for comparing each row against a future one, like computing next-day changes.
Subtracting a shifted column from the original, like the current price minus the price shifted by one, is the standard idiom for computing period-over-period change in a time series — much simpler and faster than writing a manual loop comparing each row to the previous one.
import pandas as pd
df = pd.DataFrame({"price": [100, 105, 103, 110]})
df["prev_price"] = df["price"].shift(1)
print(df)2Practical Example
Here is a real-world application of df.shift() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"price": [100, 105, 103, 110]})
df["daily_change"] = df["price"] - df["price"].shift(1)
print(df)3Best Practices
Follow these guidelines when working with df.shift():
1. Use shift() combined with subtraction or division to compute period-over-period changes, instead of writing a manual loop over rows
2. Use a negative periods value when you need to compare against a future row instead of a past one
3. Remember shift() introduces NaN at the boundary, top or bottom, it shifts away from — handle that expected missing value deliberately rather than as a surprise
Tip: Subtracting a shifted column from the original, like the current price minus the price shifted by one, is the standard idiom for computing period-over-period change in a time series — much simpler and faster than writing a manual loop comparing each row to the previous one.
import pandas as pd
df = pd.DataFrame({"price": [100, 105, 103, 110]})
df["prev_price"] = df["price"].shift(1)
print(df)