Challenge - 5 Problems
Shift Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of shift() with default parameters
What is the output of the following code snippet using pandas shift() with default lag?
Pandas
import pandas as pd df = pd.DataFrame({'value': [10, 20, 30, 40]}) df['lagged'] = df['value'].shift() print(df)
Attempts:
2 left
💡 Hint
Remember that shift() moves data down by 1 row by default, introducing NaN at the top.
✗ Incorrect
The shift() function moves the data down by one row, so the first row in the new column is NaN, and each subsequent row contains the previous row's value.
❓ data_output
intermediate2:00remaining
Result of shift() with negative periods
What is the resulting DataFrame after applying shift() with periods=-1 on the 'value' column?
Pandas
import pandas as pd df = pd.DataFrame({'value': [5, 15, 25, 35]}) df['lead'] = df['value'].shift(periods=-1) print(df)
Attempts:
2 left
💡 Hint
Negative periods shift data up, so the last row becomes NaN.
✗ Incorrect
Using periods=-1 shifts the data up by one row, so the last row in the new column is NaN, and each row contains the next row's value.
🔧 Debug
advanced2:00remaining
Identify the error in shift() usage
What error will this code raise and why?
import pandas as pd
df = pd.DataFrame({'score': [100, 200, 300]})
df['shifted'] = df['score'].shift(periods='2')
Pandas
import pandas as pd df = pd.DataFrame({'score': [100, 200, 300]}) df['shifted'] = df['score'].shift(periods='2')
Attempts:
2 left
💡 Hint
Check the type of the 'periods' argument in shift().
✗ Incorrect
The periods argument must be an integer. Passing a string like '2' causes a ValueError.
🚀 Application
advanced2:30remaining
Using shift() to calculate daily returns
Given a DataFrame with daily stock prices, which code correctly calculates the daily return as percentage change using shift()?
Pandas
import pandas as pd df = pd.DataFrame({'price': [100, 105, 110, 120]})
Attempts:
2 left
💡 Hint
Daily return is (today's price - yesterday's price) divided by yesterday's price.
✗ Incorrect
Option B correctly computes the percentage change from the previous day using shift(1).
🧠 Conceptual
expert3:00remaining
Effect of shift() on time series with missing dates
If a time series DataFrame has missing dates and you apply shift() on the value column, what is the effect on the lagged data?
Attempts:
2 left
💡 Hint
shift() works row-wise and does not modify the index or fill missing dates.
✗ Incorrect
shift() moves data down by rows without considering the index values, so missing dates cause gaps in lagged data.