import pandas as pd df = pd.DataFrame({ 'timestamp': pd.to_datetime(['2024-06-01 08:30', '2024-06-02 15:45', '2024-06-03 23:00']) }) df['day_of_week'] = df['timestamp'].dt.dayofweek df['hour'] = df['timestamp'].dt.hour print(df[['day_of_week', 'hour']])
The dayofweek attribute returns an integer where Monday=0 and Sunday=6. June 1, 2024 is a Saturday (5), June 2 is Sunday (6), and June 3 is Monday (0). The hour attribute extracts the hour part of the timestamp.
import pandas as pd df = pd.DataFrame({ 'timestamp': pd.to_datetime([ '2024-06-01 08:30', '2024-06-02 15:45', '2024-06-03 23:00', '2024-06-08 10:00', '2024-06-09 12:00' ]) }) df['day_of_week'] = df['timestamp'].dt.dayofweek unique_days = df['day_of_week'].nunique() print(unique_days)
The dates correspond to Saturday (5), Sunday (6), Monday (0), Saturday (5), and Sunday (6). So unique days are 0, 5, and 6, which is 3 unique days.
import pandas as pd df = pd.DataFrame({ 'timestamp': ['2024-06-01 08:30', '2024-06-02 15:45'] }) df['hour'] = df['timestamp'].dt.hour print(df['hour'])
The .dt accessor requires the column to be datetime type. Here, the column is string, so pandas raises an AttributeError.
import pandas as pd df = pd.DataFrame({ 'timestamp': pd.to_datetime([ '2024-06-01 17:00', '2024-06-01 19:00', '2024-06-02 20:00', '2024-06-03 21:00' ]) }) df['day_of_week'] = df['timestamp'].dt.dayofweek df['hour'] = df['timestamp'].dt.hour
Option B uses isin() correctly to check if day_of_week is Saturday (5) or Sunday (6). Options B and C use Python boolean operators incorrectly on pandas Series, and D uses in which is invalid for Series.
dt.dayofweek and dt.weekday_name in pandas?dt.dayofweek returns an integer from 0 (Monday) to 6 (Sunday). dt.weekday_name (deprecated in newer pandas versions) returns the day name as a string like 'Monday'.