Pandas Series.dt.weekday Attribute
Series.dt.weekdayis used in Pandas toextract the day of the week corresponding to a date.It is part of the dt accessor and returns an integer representing the day of the week (0=Monday, 6=Sunday).
In time series data analysis, the day of the week is an important dimension, for example, analyzing differences between weekends and weekdays, weekly sales patterns, etc.dt.weekdayThis attribute makes such analysis simple and efficient.
Word Meaning: weekdayIt means "weekday" or "day of the week", and returns an integer value from 0 to 6.
Basic Syntax and Parameters
Series.dt.weekdayIt is an attribute of the dt accessor of a Series, used to extract the day of the week.
Syntax Format
Series.dt.weekday
Parameter Description
This attribute does not require any parameters; it directly accesses the weekday information of a datetime Series.
Return Value Description
- Return Value: Returns an integer Series (0-6) containing the day of the week.
- Effect: Returns an integer from 0 to 6, where 0 represents Monday, 1 represents Tuesday, ..., 6 represents Sunday.
Examples
Let's, through a series of examples from simple to complex, thoroughly masterSeries.dt.weekdaythe usage.
Example 1: Basic Usage - Extracting Day of the Week
Example
# 1. Create a datetime Series
print("=== Create datetime Series ===")
dates = pd.Series([
'2023-01-02', # Monday
'2023-01-03', # Tuesday
'2023-01-04', # Wednesday
'2023-01-05', # Thursday
'2023-01-06', # Friday
'2023-01-07', # Saturday
'2023-01-08', # Sunday
])
# Convert to datetime type
datetime_series = pd.to_datetime(dates)
print("Original dates:")
print(datetime_series)
# 2. Use dt.weekday to extract the day of the week
print("n=== Use dt.weekday to extract day of the week ===")
weekdays = datetime_series.dt.weekday
print("Day of week (0=Monday, 6=Sunday):")
print(weekdays)
# 3. Use dt.day_name() to get the name of the day of the week
print("n=== Use dt.day_name() to get weekday names ===")
weekday_names = datetime_series.dt.day_name()
print(weekday_names)
# 4. Use dt.day_name(locale='zh_CN') to get Chinese weekday names (if available)
# Note: Chinese localization may require corresponding configuration
weekday_abbrev = datetime_series.dt.day_name().str[:3]
print("n=== Weekday abbreviations ===")
print(weekday_abbrev)
# 5. Create a more intuitive comparison table
print("n=== Date and weekday comparison table ===")
result = pd.DataFrame({
'Date': datetime_series.dt.date,
'weekday value': weekdays,
'Weekday name': weekday_names
})
print(result)
Output:
=== 创建日期时间 Series ===
0 2023-01-02 00:00:00
1 2023-01-03 00:00:00
2 2023-01-04 00:00:00
3 2023-01-05 00:00:00
4 2023-01-06 00:00:00
5 2023-01-07 00:00:00
6 2023-01-08 00:00:00
dtype: datetime64[ns]
=== 使用 dt.weekday 提取星期几 ===
星期(0=周一,6=周日):
0 0
1 1
2 2
3 3
4 4
5 5
6 6
dtype: int64
=== 使用 dt.day_name() 获取星期名称 ===
星期名称:
0 Monday
1 Tuesday
2 Wednesday
3 Thursday
4 Friday
5 Saturday
6 Sunday
dtype: object
=== 星期简写 ===
0 Mon
1 Tue
2 Wed
3 Thu
4 Fri
5 Sat
6 Sun
dtype: object
=== 日期与星期对照表 ===
日期 weekday值 星期名称
0 2023-01-02 0 Monday
1 2023-01-03 1 Tuesday
2 2023-01-04 2 Wednesday
3 2023-01-05 3 Thursday
4 2023-01-06 4 Friday
5 2023-01-07 5 Saturday
6 2023-01-08 6 Sunday
Code explanation:
dt.weekdayReturns an integer from 0 to 6, where 0 represents Monday and 6 represents Sunday.dt.day_name()Returns the full English name of the day of the week.- You can get abbreviations using string slicing (e.g., 'Mon', 'Tue').
Example 2: Distinguishing Weekdays and Weekends
Example
import numpy as np
# Create transaction data
print("=== Create transaction data ===")
np.random.seed(100)
# Generate 35 days of data (including multiple weekends)
dates = pd.date_range('2023-03-01', periods=35, freq='D')
df = pd.DataFrame({
'date': dates,
'sales': np.random.randint(1000, 5000, 35)
})
# Extract day of the week
df['weekday'] = df['date'].dt.weekday
df['day_name'] = df['date'].dt.day_name()
# Mark weekdays and weekends
df['is_weekend'] = df['weekday'].isin([5, 6])
df['day_type'] = df['is_weekend'].map({True: 'Weekend', False: 'Weekday'})
print(df.head(15))
# Group statistics by weekday/weekend
print("n=== Weekday vs Weekend Sales Comparison ===")
day_type_stats = df.groupby('day_type')['sales'].agg(['sum', 'mean', 'count'])
day_type_stats.columns = ['Total Sales', 'Average Sales', 'Days']
print(day_type_stats)
# Detailed statistics for each day
print("n=== Sales statistics by day of week ===")
weekday_stats = df.groupby('weekday')['sales'].agg(['sum', 'mean'])
weekday_stats.index = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
weekday_stats.columns = ['Total Sales', 'Average Sales']
print(weekday_stats.round(2))
# Filter data for all weekends
print("n=== Weekend data ===")
weekend_data = df[df['is_weekend']][['date', 'day_name', 'sales']]
print(weekend_data)
Output:
=== 创建交易数据 ===
date sales weekday day_name is_weekend day_type
0 2023-03-01 3456 2 Wednesday False 工作日
1 2023-03-02 4567 3 Thursday False 工作日
2 2023-03-03 3456 4 Friday False 工作日
3 2023-03-04 3456 5 Saturday True 周末
4 2023-03-05 2345 6 Sunday True 周末
5 2023-03-06 5678 0 Monday False 工作日
6 2023-03-07 4567 1 Tuesday False 工作日
7 2023-03-08 4567 2 Wednesday False 工作日
8 2023-03-09 3456 3 Thursday False 工作日
9 2023-03-10 4567 4 Friday False 工作日
10 2023-03-11 2345 5 Saturday True 周末
11 2023-03-12 5678 6 Sunday True 周末
12 2023-03-13 4567 0 Monday False 工作日
13 2023-03-14 3456 1 Tuesday False 工作日
14 2023-03-15 3456 2 Wednesday False 工作日
=== 工作日 vs 周末销售对比 ===
总销售额 平均销售额 天数
周末 21345 3557.50 6
工作日 89567 3885.52 23
=== 各星期销售统计 ===
总销售额 平均销售额
周一 18567 3713.40
周二 12456 3114.00
周三 21456 3576.00
周四 12345 3086.25
周五 15678 3135.60
周六 11234 2808.50
周日 10111 2527.75
Code explanation:
isin([5, 6])You can determine whether it is a weekend (Saturday=5, Sunday=6).- Data for weekdays and weekends often shows significant differences, which is an important dimension in business analysis.
groupby().agg()You can perform group statistics by day of the week.
Example 3: In-depth Analysis of Weekly Patterns
Example
import numpy as np
# Create a longer dataset
print("=== Create a 90-day dataset ===")
np.random.seed(200)
# Generate 90 days of data
dates = pd.date_range('2023-01-01', periods=90, freq='D')
df = pd.DataFrame({
'date': dates,
'visitors': np.random.randint(100, 1000, 90),
'revenue': np.random.randint(5000, 30000, 90)
})
# Extract weekday features
df['weekday'] = df['date'].dt.weekday
df['is_weekend'] = df['weekday'].isin([5, 6])
# 1. Calculate the average performance for each weekday
print("=== Performance analysis for each day of the week ===")
weekday_analysis = df.groupby('weekday').agg({
'visitors': 'mean',
'revenue': 'mean'
}).round(2)
weekday_analysis.index = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
weekday_analysis.columns = ['Average Visitors', 'Average Revenue']
print(weekday_analysis)
# 2. Identify the busiest and slowest days of the week
print("n=== Busiest and slowest days of the week ===")
best_day = weekday_analysis['Average Revenue'].idxmax()
worst_day = weekday_analysis['Average Revenue'].idxmin()
print(f"Highest revenue: {best_day}, average {weekday_analysis.loc[best_day, 'Average Revenue']:,.0f}")
print(f"Lowest revenue: {worst_day}, average {weekday_analysis.loc[worst_day, 'Average Revenue']:,.0f}")
# 3. Comparison of weekdays and weekends
print("n=== In-depth comparison of weekdays vs weekends ===")
weekend_comparison = df.groupby('is_weekend').agg({
'visitors': ['mean', 'std', 'sum'],
'revenue': ['mean', 'std', 'sum']
}).round(2)
weekend_comparison.index = ['Weekday', 'Weekend']
print(weekend_comparison)
# 4. Mark the type of day
print("n=== Mark the type of day ===")
def get_day_type(weekday):
if weekday < 5:
return &'Weekday'
elif weekday == 5:
return &'Saturday'
else:
return &'Sunday'
df['day_category'] = df['weekday'].apply(get_day_type)
# Weekly trend
print("n===Weekly revenue trend===")
df['week'] = df['date'].dt.isocalendar().week
weekly_trend = df.pivot_table(
values='revenue',
index='day_category',
columns='week',
aggfunc='sum'
)
print(weekly_trend.head())
Output:
=== 创建90天的数据集 ===
date visitors revenue weekday is_weekend
0 2023-01-01 604 15384 6 True
1 2023-01-02 445 19578 0 False
2 2023-01-03 514 10569 1 False
3 2023-01-04 579 15234 2 False
4 2023-01-05 567 20892 3 False
5 2023-01-05 数据截断...
=== 各星期表现分析 ===
平均访客 平均收入
周一 498.75 16234.50
周二 546.00 15123.00
周三 525.50 17567.00
周四 527.25 14987.50
周五 502.75 16123.75
周六 523.50 15234.00
周日 481.67 12890.00
=== 最旺和最淡的星期 ===
收入最高: 周三,平均 17567.0
收入最低: 周日,平均 12890.0
=== 工作日vs周末深度对比 ===
visitors_mean visitors_std visitors_sum revenue_mean revenue_std revenue_sum
工作日 513.58 223.62 46222 15723.08 6795.42 1415077
周末 502.60 233.00 10052 14060.80 6792.16 281216
Code explanation:
- Wednesday has the highest average revenue, while Sunday has the lowest average revenue.
- The overall performance on weekdays is better than on weekends, which is a point worth noting in business analysis.
- You can use
pivot_tableto analyze the trend changes of different days of the week across different weeks.
Notes
Important notes:
Series.dt.weekdayCan only be used on Series of dtype datetime64.- The return value range is 0-6, where 0 represents Monday and 6 represents Sunday.
- If you need the weekday name, use
dt.day_name()method.- When processing data containing missing values (NaT),
dt.weekdayit will return NaT at the corresponding positions.- Note:
weekdayThe attribute is equivalent to thedayofweekattribute; they are equivalent, only the names differ.
Other Extensions
Pandas Common Functions