pd.Timedelta(5) is missing the unit. It needs a keyword like days=5 or a string like '5 days'.
Step 2: Understand error cause
Without specifying units, pandas cannot interpret the number 5 alone, causing an error.
Final Answer:
Timedelta needs a unit like days=5 -> Option A
Quick Check:
Timedelta(5) missing units causes error [OK]
Hint: Always specify units when creating Timedelta [OK]
Common Mistakes:
Passing integer without units
Assuming default unit is days
Confusing Timestamp and Timedelta usage
5. You have a pandas DataFrame df with a column 'date' of type datetime. You want to create a new column 'date_plus_7' that adds 7 days to each date. Which code correctly does this?
hard
A. df['date_plus_7'] = df['date'] + pd.Timedelta('7 days')
B. df['date_plus_7'] = df['date'] + pd.Timedelta(days=7)
C. df['date_plus_7'] = df['date'] + pd.Timedelta(7)
D. df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) * len(df)
Solution
Step 1: Understand Timedelta broadcasting
Adding a Timedelta to a pandas Series of dates works if the Timedelta is a scalar (single duration).
Step 2: Check each option
df['date_plus_7'] = df['date'] + pd.Timedelta('7 days') uses a string '7 days' which works but is less common in vectorized operations. df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) uses pd.Timedelta(days=7) which is the standard and recommended way. df['date_plus_7'] = df['date'] + pd.Timedelta(7) misses units and causes error. df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) * len(df) multiplies timedelta by length, which incorrectly scales the timedelta.
Step 3: Choose the best practice
df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) is the correct and recommended way to add 7 days to each date in a column.
Final Answer:
df['date_plus_7'] = df['date'] + pd.Timedelta(days=7) -> Option B
Quick Check:
Use pd.Timedelta(days=7) for vectorized addition with Series [OK]
Hint: Use pd.Timedelta(days=7) for vectorized addition with Series [OK]
Common Mistakes:
Passing integer without units
Multiplying Timedelta by length of DataFrame
Not using vectorized Timedelta correctly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.