0
0
Pandasdata~10 mins

diff() for differences 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 calculate the difference between consecutive values in the 'sales' column.

Pandas
df['diff_sales'] = df['sales'].[1]()
Drag options to blanks, or click blank then click option'
Adiff
Bsum
Cmean
Dcumsum
Attempts:
3 left
💡 Hint
Common Mistakes
Using sum() instead of diff() which adds values instead of finding differences.
Using mean() which calculates average, not differences.
2fill in blank
medium

Complete the code to calculate the difference over 2 periods in the 'temperature' column.

Pandas
df['temp_diff_2'] = df['temperature'].diff([1])
Drag options to blanks, or click blank then click option'
A2
B1
C0
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 which is the default and only looks at the previous row.
Using 0 which returns NaN for all rows.
3fill in blank
hard

Fix the error in the code to correctly calculate the difference of the 'price' column.

Pandas
df['price_diff'] = df.price.[1]()
Drag options to blanks, or click blank then click option'
Adifference
Bdiff
Csubtract
Ddiffs
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'difference' or 'diffs' which are not pandas methods.
Using 'subtract' which is a function but not a method on Series.
4fill in blank
hard

Fill both blanks to create a new column with the difference over 3 periods for the 'stock' column.

Pandas
df['stock_diff'] = df['stock'].diff([1]).fillna([2])
Drag options to blanks, or click blank then click option'
A3
B0
CNaN
D0.0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 for periods which returns NaN for all rows.
Filling NaNs with 'NaN' string instead of numeric 0.0.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps each word to its difference in length compared to the previous word, only if the length difference is positive.

Pandas
length_diff = {word: len(word) - len(prev) for word, prev in zip(words[[1]:], words[:-[2]]) if (len(word) - len(prev)) [3] 0}
Drag options to blanks, or click blank then click option'
A1
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 for the slice which causes misalignment.
Using < instead of > which filters negative differences.