Date feature extraction in Data Analysis Python - Time & Space Complexity
We want to understand how the time to extract parts of dates grows as we handle more data.
How does the work change when we have more dates to process?
Analyze the time complexity of the following code snippet.
import pandas as pd
dates = pd.Series(pd.date_range('2023-01-01', periods=1000))
# Extract year, month, day from each date
features = pd.DataFrame({
'year': dates.dt.year,
'month': dates.dt.month,
'day': dates.dt.day
})
This code creates a list of dates and extracts year, month, and day parts into a new table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Extracting year, month, and day from each date in the list.
- How many times: Once for each date in the input series.
Each date is processed individually to get its parts, so the work grows directly with the number of dates.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 (3 parts x 10 dates) |
| 100 | About 300 (3 parts x 100 dates) |
| 1000 | About 3000 (3 parts x 1000 dates) |
Pattern observation: The total work increases steadily as we add more dates, roughly multiplying by the number of dates.
Time Complexity: O(n)
This means the time to extract date parts grows in a straight line with the number of dates.
[X] Wrong: "Extracting multiple parts from dates takes the same time no matter how many dates there are."
[OK] Correct: Each date must be processed separately, so more dates mean more work and more time.
Understanding how data size affects processing time helps you explain your code choices clearly and shows you think about efficiency.
"What if we extracted more features like hour, minute, and second? How would the time complexity change?"
Practice
dt.year attribute do when applied to a pandas datetime column?Solution
Step 1: Understand pandas datetime accessor
Thedtaccessor allows extraction of date parts from datetime columns.Step 2: Identify what
dt.yearextractsdt.yearextracts the year component from each datetime value.Final Answer:
Extracts the year part from each date in the column -> Option AQuick Check:
dt.year = year extraction [OK]
- Confusing dt.year with dt.day or dt.month
- Thinking dt.year converts dates to strings
- Assuming dt.year calculates date differences
df['date']?Solution
Step 1: Recall pandas datetime accessor usage
To extract date parts, pandas requires thedtaccessor before the attribute.Step 2: Identify correct syntax for month extraction
The correct syntax isdf['date'].dt.month. Other options are invalid methods or missingdt.Final Answer:
df['date'].dt.month -> Option BQuick Check:
Use dt.month to get month [OK]
- Omitting .dt accessor
- Using non-existent methods like get_month()
- Trying to extract with extract('month')
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())Solution
Step 1: Convert dates to day of week numbers
Usingdt.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 DQuick Check:
Sunday=6, Tuesday=1, Sunday=6 [OK]
- Confusing dayofweek with weekday names
- Assuming Sunday=0 instead of 6
- Mixing up dayofweek and day_name()
df['timestamp']?
df['hour'] = df['timestamp'].hour
Solution
Step 1: Check pandas datetime attribute access
Datetime properties require thedtaccessor to access parts like hour.Step 2: Identify missing .dt in code
The code usesdf['timestamp'].hourwhich is invalid; it should bedf['timestamp'].dt.hour.Final Answer:
Missing .dt accessor before .hour -> Option AQuick Check:
Use .dt.hour to extract hour [OK]
- Trying to access .hour directly on Series
- Converting datetime to string unnecessarily
- Using .time.hour which is invalid in pandas
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?Solution
Step 1: Understand dayofweek values for weekend
In pandas,dt.dayofweekreturns 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 usesdf['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 CQuick Check:
Weekend days are dayofweek >= 5 [OK]
- Using 'in' without vectorized methods
- Using 'or' instead of bitwise operators
- Confusing dayofweek numbers or names
Ready to prove it?
Pass the test and this pattern moves unknown
