Using dt.dayofweek, Monday=0 ... Sunday=6. Dates: 2023-01-15 is Sunday (6), 2023-07-04 is Tuesday (1), 2023-12-31 is Sunday (6).
Step 2: List the dayofweek values
The list is [6, 1, 6].
Final Answer:
[6, 1, 6] -> Option D
Quick Check:
Sunday=6, Tuesday=1, Sunday=6 [OK]
Hint: Remember Monday=0, Sunday=6 for dayofweek [OK]
Common Mistakes:
Confusing dayofweek with weekday names
Assuming Sunday=0 instead of 6
Mixing up dayofweek and day_name()
4. What is wrong with this code snippet to extract the hour from a datetime column df['timestamp']?
df['hour'] = df['timestamp'].hour
medium
A. Missing .dt accessor before .hour
B. The column must be converted to string first
C. The .hour attribute does not exist in pandas
D. The code should use .time.hour instead
Solution
Step 1: Check pandas datetime attribute access
Datetime properties require the dt accessor to access parts like hour.
Step 2: Identify missing .dt in code
The code uses df['timestamp'].hour which is invalid; it should be df['timestamp'].dt.hour.
Final Answer:
Missing .dt accessor before .hour -> Option A
Quick Check:
Use .dt.hour to extract hour [OK]
Hint: Always use .dt before date parts like hour [OK]
Common Mistakes:
Trying to access .hour directly on Series
Converting datetime to string unnecessarily
Using .time.hour which is invalid in pandas
5. You have a pandas DataFrame df with a datetime column 'order_date'. You want to create a new column 'is_weekend' that is True if the order was placed on Saturday or Sunday, and False otherwise. Which code snippet correctly achieves this?
hard
A. df['is_weekend'] = df['order_date'].dt.dayofweek == 6 or 5
B. df['is_weekend'] = df['order_date'].dt.weekday in [5,6]
C. df['is_weekend'] = df['order_date'].dt.dayofweek >= 5
D. df['is_weekend'] = df['order_date'].dt.day_name() in ['Saturday', 'Sunday']
Solution
Step 1: Understand dayofweek values for weekend
In pandas, dt.dayofweek returns 0 for Monday through 6 for Sunday. Weekend days are 5 (Saturday) and 6 (Sunday).
Step 2: Check which code correctly marks weekend
df['is_weekend'] = df['order_date'].dt.dayofweek >= 5 uses df['order_date'].dt.dayofweek >= 5, which is True for 5 and 6, correctly marking weekends. Other options use invalid syntax or incorrect logic.
Final Answer:
df['is_weekend'] = df['order_date'].dt.dayofweek >= 5 -> Option C
Quick Check:
Weekend days are dayofweek >= 5 [OK]
Hint: Weekend days have dayofweek 5 or 6, use >= 5 [OK]
Common Mistakes:
Using 'in' without vectorized methods
Using 'or' instead of bitwise operators
Confusing dayofweek numbers or names
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.