Shift and lag operations in Data Analysis Python - Time & Space Complexity
We want to understand how the time it takes to perform shift and lag operations changes as the data size grows.
Specifically, we ask: how does the work increase when we shift or lag a column in a dataset?
Analyze the time complexity of the following code snippet.
import pandas as pd
n = 10 # example size
data = pd.DataFrame({'values': range(n)})
data['lagged'] = data['values'].shift(1)
This code creates a column with values shifted down by one row, introducing a lag.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The shift method moves each value down by one position in the column.
- How many times: It processes each of the n rows once to create the lagged column.
As the number of rows n increases, the operation must move each value once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 moves |
| 100 | 100 moves |
| 1000 | 1000 moves |
Pattern observation: The work grows directly with the number of rows, so doubling rows doubles the work.
Time Complexity: O(n)
This means the time to shift or lag grows linearly with the number of rows in the data.
[X] Wrong: "Shift or lag operations are constant time because they just move data by one position."
[OK] Correct: Even though the shift is by one position, the operation must touch every row to create the new column, so time grows with data size.
Understanding how simple data transformations scale helps you explain your code's efficiency clearly and confidently in real projects or interviews.
"What if we shifted by k positions instead of 1? How would the time complexity change?"
Practice
shift(1) function do to a pandas DataFrame column?Solution
Step 1: Understand the shift function
Theshift(1)moves data down by one row, so each value is replaced by the previous row's value.Step 2: Identify lag vs lead
Positive shift values create lag (previous rows), soshift(1)creates lag by one row.Final Answer:
Moves the data down by one row, creating a lag of previous values -> Option AQuick Check:
shift(1) = lag by 1 row [OK]
- Confusing shift(1) with shift(-1)
- Thinking shift sorts data
- Assuming shift removes rows
'prev_value' that contains the previous row's value of column 'value' in pandas?Solution
Step 1: Recall pandas shift syntax
The correct syntax is to callshift()on the Series, likedf['value'].shift(1).Step 2: Check each option
df['prev_value'] = df['value'].shift(1) uses correct syntax. df['prev_value'] = df['value'].shift(-1) shifts in the wrong direction. df['prev_value'] = df.shift('value', 1) uses wrong method call. df['prev_value'] = shift(df['value'], 1) uses undefined function.Final Answer:
df['prev_value'] = df['value'].shift(1) -> Option DQuick Check:
Correct pandas shift syntax = df['prev_value'] = df['value'].shift(1) [OK]
Series.shift(n) to lag by n rows [OK]- Using negative shift for previous row
- Calling shift on DataFrame with wrong arguments
- Using undefined shift function
import pandas as pd
df = pd.DataFrame({'value': [10, 20, 30, 40]})
df['lag1'] = df['value'].shift(1)
df['lead1'] = df['value'].shift(-1)
print(df)What is the output?
Solution
Step 1: Calculate lag1 column
shift(1)moves values down by one, so first row is NaN, second row gets 10, third 20, fourth 30.Step 2: Calculate lead1 column
shift(-1)moves values up by one, so last row is NaN, third row gets 40, second 30, first 20.Final Answer:
value lag1 lead1 0 10 NaN 20.0 1 20 10.0 30.0 2 30 20.0 40.0 3 40 30.0 NaN -> Option CQuick Check:
Positive shift = lag, negative shift = lead [OK]
- Mixing lag and lead directions
- Forgetting NaN appears at shifted edges
- Confusing shift with sorting
df['prev'] = df.shift(1)['value']
Assuming
df is a pandas DataFrame with a column 'value'.Solution
Step 1: Understand what df.shift(1) does
df.shift(1)shifts the entire DataFrame down by one row, including all columns.Step 2: Check indexing and efficiency
Accessing ['value'] after shift works, but shifting entire DataFrame is inefficient if only one column is needed.Final Answer:
It shifts the entire DataFrame, not just the 'value' column, which is inefficient -> Option BQuick Check:
Shift on DataFrame shifts all columns [OK]
- Assuming shift returns Series when called on DataFrame
- Expecting syntax error from indexing
- Ignoring performance impact
df with a column 'sales'. You want to create a new column 'pct_change' that shows the percentage change from the previous day. Which code correctly uses shift to calculate this?Solution
Step 1: Understand percentage change formula
Percentage change = (current - previous) / previous * 100.Step 2: Apply shift to get previous value
df['sales'].shift(1)gives previous day's sales, so formula in df['pct_change'] = (df['sales'] - df['sales'].shift(1)) / df['sales'].shift(1) * 100 matches the formula.Step 3: Check other options
df['pct_change'] = (df['sales'].shift(1) - df['sales']) / df['sales'] * 100 reverses numerator and denominator incorrectly. df['pct_change'] = df['sales'].pct_change(1) uses built-in method but question asks for shift usage. df['pct_change'] = df['sales'].shift(-1) / df['sales'] * 100 uses lead instead of lag.Final Answer:
df['pct_change'] = (df['sales'] - df['sales'].shift(1)) / df['sales'].shift(1) * 100 -> Option AQuick Check:
Percentage change uses lag with shift(1) [OK]
- Using shift(-1) instead of shift(1)
- Reversing numerator and denominator
- Confusing built-in pct_change with manual shift
Ready to prove it?
Pass the test and this pattern moves unknown
