Pandas Series.dt.weekday Attribute
Series.dt.weekday is a Pandas attribute used toextracts the day of the week corresponding to a dateIt 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 the difference between weekends and weekdays, weekly sales patterns, and so on.dt.weekday The attribute makes this kind of analysis simple and efficient.
Word meaning: weekday means "weekday" or "day of the week", returning an integer value from 0 to 6.
Basic syntax and parameters
Series.dt.weekday It is an attribute of the dt accessor of Series, used to extract the day of the week.
Syntax format
Series.dt.weekday
Parameter Description
This attribute requires no arguments; simply access the week information of a datetime Series.
Return value description
- Return Value: Returns an integer Series containing the days of the week (0-6).
- effect: Returns an integer from 0 to 6, where 0 means Monday, 1 means Tuesday, ..., and 6 means Sunday.
Example
Let us thoroughly master Series.dt.weekday through a series of examples from simple to complex.
Example 1: Basic Usage - Extracting the Day of the Week
Example
import
pandas
as
pd
1. Create a Series of datetimes
(
"=== Create a 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
)
(
"Original dates:"
)
(
datetime_series
)
2. Extract the Day of the Week Using dt.weekday
(
"n=== Extracting the Day of the Week Using dt.weekday ==="
)
weekdays
=
datetime_series.
dt
.
weekday
(
"Weekday (0=Monday, 6=Sunday):"
)
(
weekdays
)
3. Use dt.day_name() to Get the Names of the Weekdays
(
"n=== Getting Weekday Names Using dt.day_name() ==="
)
weekday_names
=
datetime_series.
dt
.
day_name
(
)
(
weekday_names
)
4. Use dt.day_name(locale='zh_CN') to Get Chinese Weekday Names (If Available)
Note: Chinese localization may require appropriate configuration
weekday_abbrev
=
datetime_series.
dt
.
day_name
(
)
.
str
[
:
3
]
(
"n=== Weekday Abbreviations ==="
)
(
weekday_abbrev
)
5. Create a More Intuitive Comparison Table
(
"n=== Date and Weekday Comparison Table ==="
)
result
=
pd.
DataFrame
(
{
'Date'
: datetime_series.
dt
.
date
,
'weekday Value'
: weekdays
,
'Weekday Name'
: weekday_names
}
)
(
result
)
Result:
=== 创建日期时间 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() 获取星期名称 ===
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 analysis:
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 weekday.- You can get abbreviations through string slicing (such as 'Mon', 'Tue').
Example 2: Distinguishing Weekdays from Weekends
Example
import
pandas
as
pd
import
numpy
as
np
Create transaction data
(
"=== Create Transaction Data ==="
)
np.
random
.
seed
(
100
)
Generate 35 days of data (including several 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 the day of the week
df
[
'weekday'
]
=
df
[
'date'
]
.
dt
.
weekday
df
[
'day_name'
]
=
df
[
'date'
]
.
dt
.
day_name
(
)
Label weekdays and weekends
df
[
'is_weekend'
]
=
df
[
'weekday'
]
.
isin
(
[
5
,
6
]
)
df
[
'day_type'
]
=
df
[
'is_weekend'
]
.
map
(
{
True
:
'Weekend'
,
False
:
'Weekday'
}
)
(
df.
head
(
15
)
)
Aggregate by weekday/weekend
(
"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'
]
(
day_type_stats
)
Drill down to statistics for each day
(
"n=== Sales Statistics by Weekday ==="
)
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'
]
(
weekday_stats.
round
(
2
)
)
Filter all weekend data
(
"n=== Weekend Data ==="
)
weekend_data
=
df
[
df
[
'is_weekend'
]
]
[
[
'date'
,
'day_name'
,
'sales'
]
]
(
weekend_data
)
Result:
=== 创建交易数据 ===
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 analysis:
isin([5, 6])You can determine whether a date falls on a weekend (Saturday=5, Sunday=6).- Data for weekdays and weekends often differ significantly, which is an important dimension in business analysis.
groupby().agg()You can group and aggregate by day of the week.
Example 3: In-Depth Analysis of Weekly Patterns
Example
import
pandas
as
pd
import
numpy
as
np
Create a dataset spanning a longer period
(
"=== 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 of Each Weekday
(
"=== Performance Analysis by Weekday ==="
)
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'
]
(
weekday_analysis
)
2. Identify the Peak and Off-Peak Weekdays
(
"n=== Peak and Off-Peak Weekdays ==="
)
best_day
=
weekday_analysis
[
'Average Revenue'
]
.
idxmax
(
)
worst_day
=
weekday_analysis
[
'Average Revenue'
]
.
idxmin
(
)
(
f
"Highest revenue: {best_day}, average {weekday_analysis.loc[best_day, 'Average Revenue']:,.0f}"
)
(
f
"Lowest revenue: {worst_day}, average {weekday_analysis.loc[worst_day, 'Average Revenue']:,.0f}"
)
3. Weekday and Weekend Comparison
(
"n=== In-Depth Weekday vs Weekend Comparison ==="
)
weekend_comparison
=
df.
groupby
(
'is_weekend'
)
.
agg
(
{
'visitors'
:
[
'mean'
,
'std'
,
'sum'
]
,
'revenue'
:
[
'mean'
,
'std'
,
'sum'
]
}
)
.
round
(
2
)
weekend_comparison.
index
=
[
'Weekday'
,
'Weekend'
]
(
weekend_comparison
)
4. Label Workday Types
(
"n=== Labeling Workday Types ==="
)
def
get_day_type
(
weekday
)
:
if
weekday <
;
5
:
return
&
#039;Workday'
elif
weekday
==
5
:
return
&
#039;Saturday'
else
:
return
&
#039;Sunday'
df
[
&
#039;day_category'] = df['weekday'].apply(get_day_type)
Weekly trends
(
"
;
n
===
Weekly revenue trends
===
"
;
)
df
[
&
#039;week'] = df['date'].dt.isocalendar().week
weekly_trend
=
df.
pivot_table
(
values
=
&
#039;revenue',
index
=
&
#039;day_category',
columns
=
&
#039;week',
aggfunc
=
&
#039;sum'
)
(
weekly_trend.
head
(
)
)
Result:
=== 创建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 analysis:
- Wednesday has the highest average revenue, while Sunday has the lowest.
- Weekdays perform better overall than weekends, which is a point worth noting in business analysis.
- You can use the
pivot_tableAnalyze how the trend for each weekday changes across different weeks.
Notes
Important note:
Series.dt.weekday It can only be used with a Series of dtype datetime64.dt.day_name() method.dt.weekday NaT is returned at the corresponding positions.weekday The attribute and dayofweek attribute are equivalent, differing only in name.
Common Pandas functions