Pandas Series Dt Weekday
[ Pandas Common Functions](#)
* * *
`Series.dt.weekday` is an attribute in Pandas used to **extract the day of the week** from dates. 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. The `dt.weekday` attribute makes such analysis simple and efficient.
**Word Explanation**: `weekday` means "day of the week" or "weekday", returning integer values from 0-6.
* * *
## Basic Syntax and Parameters
`Series.dt.weekday` is an attribute of the dt accessor in Series, used to extract the day of the week.
### Syntax Format
Series.dt.weekday
### Parameter Description
This attribute requires no parameters; directly access the day-of-week information of a datetime Series.
### Return Value Description
* **Return Value**: Returns an integer Series containing the day of the week (0-6).
* **Effect**: Returns integers from 0-6, where 0 represents Monday, 1 represents Tuesday, ..., 6 represents Sunday.
* * *
## Examples
Let's thoroughly master the usage of `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 date times
print("=== Creating 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=== Using 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=== Using dt.day_name() to get day names ===")
weekday_names = datetime_series.dt.day_name()
print(weekday_names)
# 4. Use dt.day_name(locale='zh_CN') to get Chinese day names (if available)
# Note: Chinese localization may require corresponding configuration
weekday_abbrev = datetime_series.dt.day_name().str[:3]
print("n=== Day abbreviations ===")
print(weekday_abbrev)
# 5. Create a more intuitive comparison table
print("n=== Date and day of week comparison table ===")
result = pd.DataFrame({
'Date': datetime_series.dt.date,
'weekday_value': weekdays,
'Day_name': weekday_names
})
print(result)
**Output:**
=== Creating DateTime Series ===0 2023-01-02 00:00:001 2023-01-03 00:00:002 2023-01-04 00:00:003 2023-01-05 00:00:004 2023-01-06 00:00:005 2023-01-07 00:00:006 2023-01-08 00:00:00 dtype: datetime64=== Using dt.weekday to extract day of the week ===Day of week (0=Monday, 6=Sunday):0 01 12 23 34 45 56 6 dtype: int64 === Using dt.day_name() to get day names ===Day names:0 Monday1 Tuesday2 Wednesday3 Thursday4 Friday5 Saturday6 Sunday dtype: object=== Day abbreviations ===0 Mon1 Tue2 Wed3 Thu4 Fri5 Sat6 Sun dtype: object=== Date and day of week comparison table === Date weekday_value Day_name0 2023-01-02 0 Monday1 2023-01-03 1 Tuesday2 2023-01-04 2 Wednesday3 2023-01-05 3 Thursday4 2023-01-06 4 Friday5 2023-01-07 5 Saturday6 2023-01-08 6 Sunday
**Code Analysis:**
1. `dt.weekday` returns integers from 0-6, where 0 represents Monday and 6 represents Sunday.
2. `dt.day_name()` returns the full English name of the day of the week.
3. You can use string slicing to get abbreviations (e.g., 'Mon', 'Tue').
### Example 2: Distinguishing Weekdays and Weekends
## Example
import pandas as pd
import numpy as np
# Create transaction data
print("=== Creating transaction data ===")
np.random.seed(100)
# Generate 35 days of data (includes 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 all weekend data
print("n=== Weekend data ===")
weekend_data = df[df['is_weekend']][['date','day_name','sales']]
print(weekend_data)
**Output:**
=== Creating transaction data === date sales weekday day_name is_weekend day_type 0 2023-03-01 3456 2 Wednesday False Weekday1 2023-03-02 4567 3 Thursday False Weekday2 2023-03-03 3456 4 Friday False Weekday3 2023-03-04 3456 5 Saturday True Weekend4 2023-03-05 2345 6 Sunday True Weekend5 2023-03-06 5678 0 Monday False Weekday6 2023-03-07 4567 1 Tuesday False Weekday7 2023-03-08 4567 2 Wednesday False Weekday8 2023-03-09 3456 3 Thursday False Weekday9 2023-03-10 4567 4 Friday False Weekday10 2023-03-11 2345 5 Saturday True Weekend11 2023-03-12 5678 6 Sunday True Weekend12 2023-03-13 4567 0 Monday False Weekday13 2023-03-14 3456 1 Tuesday False Weekday14 2023-03-15 3456 2 Wednesday False Weekday=== Weekday vs Weekend sales comparison === Total_sales Average_sales DaysWeekend 21345 3557.50 6Weekday 89567 3885.52 23=== Sales statistics by day of week === Total_sales Average_salesMonday 18567 3713.40Tuesday 12456 3114.00Wednesday 21456 3576.00Thursday 12345 3086.25Friday 15678 3135.60Saturday 11234 2808.50Sunday 10111 2527.75
**Code Analysis:**
* `isin([5, 6])` can determine whether it's 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()` can perform grouped statistics by day of the week.
### Example 3: In-depth Analysis of Weekly Patterns
## Example
import pandas as pd
import numpy as np
# Create a longer-term dataset
print("=== Creating 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 day of week features
df['weekday']= df['date'].dt.weekday
df['is_weekend']= df['weekday'].isin([5,6])
# 1. Calculate average performance for each day of the week
print("=== Analysis of performance by day of 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 strongest and weakest days
print("n=== Strongest and weakest days ===")
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. Weekday and weekend comparison
print("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']
print(weekend_comparison)
# 4. Mark day type
print("n=== Marking day types ===")
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 trends
print("n=== Weekly revenue trends ===")
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:**
=== Creating 90-day dataset === date visitors revenue weekday is_weekend 0 2023-01-01 604 15384 6 True1 2023-01-02 445 19578 0 False2 2023-01-03 514 10569 1 False3 2023-01-04 579 15234 2 False4 2023-01-05 567 20892 3 False5 2023-01-05 Data truncated...=== Analysis of performance by day of week === Average_visitors Average_revenueMonday 498.75 16234.50Tuesday 546.00 15123.00Wednesday 525.50 17567.00Thursday 527.25 14987.50Friday 502.75 16123.75Saturday 523.50 15234.00Sunday 481.67 12890.00=== Strongest and weakest days ===Highest revenue: Wednesday, average 17567.0Lowest revenue: Sunday, average 12890.0=== In-depth weekday vs weekend comparison === visitors_mean visitors_std visitors_sum revenue_mean revenue_std revenue_sum Weekday 513.58 223.62 46222 15723.08 6795.42 1415077Weekend 502.60 233.00 10052 14060.80 6792.16 281216
**Code Analysis:**
* Wednesday has the highest average revenue, while Sunday has the lowest average revenue.
* Overall performance on weekdays is better than weekends, which is a noteworthy point in business analysis.
* You can use `pivot_table` to analyze trend changes for different days across different weeks.
## Notes
> **Important Notes:**
>
>
> * `Series.dt.weekday` can only be used for Series of datetime64 type.
> * The return value range is 0-6, where 0 represents Monday and 6 represents Sunday.
> * If you need day names, use the `dt.day_name()` method.
> * When handling data containing missing values (NaT), `dt.weekday` will return NaT at the corresponding position.
> * Note: The `weekday` attribute and `dayofweek` attribute are equivalent, just with different names.
* * Pandas Common Functions](#)
YouTip