0
0
Pandasdata~10 mins

shift() for lagging data in Pandas - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Afillna
Bsort
Cdrop
Dshift
Attempts:
3 left
💡 Hint
Common Mistakes
Using sort() instead of shift()
Using drop() which removes data
Using fillna() which fills missing values
2fill in blank
medium

Complete 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'
Ashift
Bdrop
Csort
Dfillna
Attempts:
3 left
💡 Hint
Common Mistakes
Using fillna() which fills missing values
Using sort() which changes order
Using drop() which removes data
3fill in blank
hard

Fix 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'
Ashift
Bsort_values
Cfillna
Ddropna
Attempts:
3 left
💡 Hint
Common Mistakes
Using sort_values() which sorts data
Using fillna() which fills missing values
Using dropna() which removes missing values
4fill in blank
hard

Fill 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'
Ashift
B1
C2
Dfillna
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
5fill in blank
hard

Fill 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'
Ashift
Bfillna
Cffill
Dbfill
Attempts:
3 left
💡 Hint
Common Mistakes
Using bfill instead of ffill
Wrong order of shift and fillna
Forgetting method in fillna