Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new column 'lag_1' that contains the previous row's 'value' using shift().
Pandas
df['lag_1'] = df['value'].[1](1)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using sort() instead of shift()
Using drop() which removes data
Using fillna() which fills missing values
✗ Incorrect
The shift() function moves the data down by the specified number of periods, creating lagged values.
2fill in blank
mediumComplete the code to calculate the difference between 'value' and its lagged version 'lag_1'.
Pandas
df['diff'] = df['value'] - df['value'].[1](1)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using fillna() which fills missing values
Using sort() which changes order
Using drop() which removes data
✗ Incorrect
Using shift(1) gets the previous row's value to subtract from the current row's value.
3fill in blank
hardFix the error in the code to create a lagged column 'lag_2' with a lag of 2 rows.
Pandas
df['lag_2'] = df['value'].[1](2)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using sort_values() which sorts data
Using fillna() which fills missing values
Using dropna() which removes missing values
✗ Incorrect
shift(2) correctly shifts the data by 2 rows to create a lag of 2.
4fill in blank
hardFill both blanks to create a new column 'pct_change' that calculates the percent change from the previous row.
Pandas
df['pct_change'] = (df['value'] - df['value'].[1]([2])) / df['value'].[1](1) * 100
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using shift(2) instead of shift(1) for previous row
Using fillna() inside the calculation
Using wrong numbers for lag
✗ Incorrect
shift(1) gets the previous row's value to calculate the percent change.
5fill in blank
hardFill all three blanks to create a lagged column 'lag_1' and fill NaNs forward using fillna.
Pandas
df['lag_1'] = df['value'].[1](1).[2](method='[3]')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using bfill instead of ffill
Wrong order of shift and fillna
Forgetting method in fillna
✗ Incorrect
shift(1) creates the lag introducing NaN at the start, fillna(method='ffill') propagates the first non-NaN value forward to fill NaNs.