Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Date feature extraction in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Date Feature Extraction Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Extracting Month and Day from Dates
What is the output of the following code that extracts the month and day from a pandas datetime column?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'date': pd.to_datetime(['2023-01-15', '2023-07-04', '2023-12-31'])})
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
print(df[['month', 'day']].to_dict(orient='list'))
A{"month": [1, 7, 12], "day": [15, 4, 31]}
B{"month": [15, 4, 31], "day": [1, 7, 12]}
C{"month": [2023, 2023, 2023], "day": [15, 4, 31]}
D{"month": [1, 7, 12], "day": [2023, 2023, 2023]}
Attempts:
2 left
💡 Hint
Look at how pandas datetime properties .dt.month and .dt.day extract parts of the date.
❓ data_output
intermediate
2:00remaining
Counting Weekdays in a Date Range
Given a date range, how many Mondays are there in the DataFrame after extracting the weekday?
Data Analysis Python
import pandas as pd

dates = pd.date_range(start='2023-01-01', end='2023-01-31')
df = pd.DataFrame({'date': dates})
df['weekday'] = df['date'].dt.day_name()
monday_count = df[df['weekday'] == 'Monday'].shape[0]
print(monday_count)
A3
B4
C6
D5
Attempts:
2 left
💡 Hint
Count how many Mondays fall between Jan 1 and Jan 31, 2023.
❓ visualization
advanced
3:00remaining
Plotting Hourly Distribution of Events
Which option produces the correct bar plot showing counts of events per hour from a datetime column?
Data Analysis Python
import pandas as pd
import matplotlib.pyplot as plt

# Sample data
timestamps = pd.to_datetime([
    '2023-06-01 08:15', '2023-06-01 08:45', '2023-06-01 09:00',
    '2023-06-01 10:30', '2023-06-01 10:45', '2023-06-01 10:50'
])
df = pd.DataFrame({'timestamp': timestamps})
df['hour'] = df['timestamp'].dt.hour
counts = df['hour'].value_counts().sort_index()

plt.bar(counts.index, counts.values)
plt.xlabel('Hour of Day')
plt.ylabel('Event Count')
plt.title('Events per Hour')
plt.show()
AA line chart showing event counts over hours 8 to 10.
BA bar chart with bars at hours 8, 9, and 10 with heights 2, 1, and 3 respectively.
CA pie chart showing percentage of events per hour.
DA scatter plot with hours on x-axis and event counts on y-axis.
Attempts:
2 left
💡 Hint
Look for a bar chart with counts grouped by hour.
🔧 Debug
advanced
2:00remaining
Identifying Error in Date Extraction Code
What error does the following code raise when trying to extract the week number from a datetime column?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'date': pd.to_datetime(['2023-01-01', '2023-06-15'])})
df['week_num'] = df['date'].dt.week
print(df)
AKeyError: 'week_num'
BTypeError: dt.week is not callable
CAttributeError: 'DatetimeProperties' object has no attribute 'week'
DNo error, prints week numbers correctly
Attempts:
2 left
💡 Hint
Check if .dt.week is a valid attribute in pandas datetime accessor.
🚀 Application
expert
3:00remaining
Calculating Age from Birthdate Column
Given a DataFrame with a 'birthdate' column, which option correctly calculates the age in years as of today?
Data Analysis Python
import pandas as pd
from datetime import datetime

df = pd.DataFrame({'birthdate': pd.to_datetime(['1990-05-15', '2000-12-01', '1985-07-30'])})

# Calculate age here

print(df['age'].tolist())
Adf['age'] = (pd.to_datetime('today') - df['birthdate']).dt.days // 365
Bdf['age'] = datetime.now().year - df['birthdate'].dt.year
Cdf['age'] = (datetime.now() - df['birthdate']).days // 365
Ddf['age'] = (pd.Timestamp(datetime.now()) - df['birthdate']).dt.days // 365
Attempts:
2 left
💡 Hint
Use pandas datetime subtraction and .dt.days to get days difference.

Practice

(1/5)
1. What does the dt.year attribute do when applied to a pandas datetime column?
easy
A. Extracts the year part from each date in the column
B. Extracts the day of the week as a number
C. Converts the date to a string format
D. Calculates the difference between dates

Solution

  1. Step 1: Understand pandas datetime accessor

    The dt accessor allows extraction of date parts from datetime columns.
  2. Step 2: Identify what dt.year extracts

    dt.year extracts the year component from each datetime value.
  3. Final Answer:

    Extracts the year part from each date in the column -> Option A
  4. Quick Check:

    dt.year = year extraction [OK]
Hint: Remember dt.year gives the year number from dates [OK]
Common Mistakes:
  • Confusing dt.year with dt.day or dt.month
  • Thinking dt.year converts dates to strings
  • Assuming dt.year calculates date differences
2. Which of the following is the correct syntax to extract the month from a pandas datetime column named df['date']?
easy
A. df['date'].month
B. df['date'].dt.month
C. df['date'].get_month()
D. df['date'].extract('month')

Solution

  1. Step 1: Recall pandas datetime accessor usage

    To extract date parts, pandas requires the dt accessor before the attribute.
  2. Step 2: Identify correct syntax for month extraction

    The correct syntax is df['date'].dt.month. Other options are invalid methods or missing dt.
  3. Final Answer:

    df['date'].dt.month -> Option B
  4. Quick Check:

    Use dt.month to get month [OK]
Hint: Use .dt before date parts like month or day [OK]
Common Mistakes:
  • Omitting .dt accessor
  • Using non-existent methods like get_month()
  • Trying to extract with extract('month')
3. Given the following code, what will be the output?
import pandas as pd
dates = pd.to_datetime(['2023-01-15', '2023-07-04', '2023-12-31'])
df = pd.DataFrame({'date': dates})
df['day_of_week'] = df['date'].dt.dayofweek
print(df['day_of_week'].tolist())
medium
A. [6, 1, 0]
B. [0, 1, 6]
C. [6, 2, 6]
D. [6, 1, 6]

Solution

  1. Step 1: Convert dates to day of week numbers

    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).
  2. Step 2: List the dayofweek values

    The list is [6, 1, 6].
  3. Final Answer:

    [6, 1, 6] -> Option D
  4. 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

  1. Step 1: Check pandas datetime attribute access

    Datetime properties require the dt accessor to access parts like hour.
  2. Step 2: Identify missing .dt in code

    The code uses df['timestamp'].hour which is invalid; it should be df['timestamp'].dt.hour.
  3. Final Answer:

    Missing .dt accessor before .hour -> Option A
  4. 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

  1. 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).
  2. 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.
  3. Final Answer:

    df['is_weekend'] = df['order_date'].dt.dayofweek >= 5 -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard