0
0
Pandasdata~10 mins

Date arithmetic with timedelta 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 add 7 days to the date in the 'date' column.

Pandas
import pandas as pd
from datetime import timedelta

df = pd.DataFrame({'date': pd.to_datetime(['2024-01-01', '2024-01-02'])})
df['new_date'] = df['date'] + [1](days=7)
print(df)
Drag options to blanks, or click blank then click option'
Atimedelta
Bdatetime
Cdate
Dtime
Attempts:
3 left
💡 Hint
Common Mistakes
Using datetime instead of timedelta causes an error.
Trying to add an integer directly to a datetime column.
2fill in blank
medium

Complete the code to subtract 3 days from the 'date' column.

Pandas
import pandas as pd
from datetime import timedelta

df = pd.DataFrame({'date': pd.to_datetime(['2024-03-10', '2024-03-15'])})
df['earlier_date'] = df['date'] - [1](days=3)
print(df)
Drag options to blanks, or click blank then click option'
Adatetime
Btime
Cdate
Dtimedelta
Attempts:
3 left
💡 Hint
Common Mistakes
Using datetime instead of timedelta.
Trying to subtract an integer directly from a datetime column.
3fill in blank
hard

Fix the error in the code to add 10 days to the 'date' column.

Pandas
import pandas as pd
from datetime import timedelta

df = pd.DataFrame({'date': pd.to_datetime(['2024-05-01', '2024-05-02'])})
df['future_date'] = df['date'] + [1](10)
print(df)
Drag options to blanks, or click blank then click option'
Atime
Btimedelta
Cdate
Ddatetime
Attempts:
3 left
💡 Hint
Common Mistakes
Using datetime instead of timedelta.
Not specifying days=10, which can cause confusion.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their lengths if length is greater than 4.

Pandas
words = ['apple', 'bat', 'grape', 'kiwi']
lengths = {word: [1] for word in words if [2]
print(lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Clen(word) > 4
Dword > 4
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as value instead of its length.
Using the word variable in the condition instead of its length.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase words as keys and their lengths if length is greater than 3.

Pandas
words = ['dog', 'cat', 'elephant', 'fox']
result = { [1]: [2] for word in words if [3] }
print(result)
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
Clen(word) > 3
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the original word as key instead of uppercase.
Using the word itself as value instead of length.
Incorrect condition for filtering words.