Pandas Series.dt.month Attribute
Series.dt.month is a Pandas attribute used toextract the month from a datetimeIt is part of the dt accessor and can quickly extract month information (1-12) from a datetime Series.
In time series data analysis, analyzing by month is a common requirement, such as monthly reports and seasonal analysis.dt.month attribute makes such operations simple and efficient.
Word meaning: month means "month", that is, it returns the month portion of a date (1 to 12).
Basic syntax and parameters
Series.dt.month It is an attribute of the dt accessor of Series, used to extract the month.
Syntax format
Series.dt.month
Parameter Description
This attribute requires no arguments; simply access the month information of a datetime Series.
Return value description
- Return Value: Returns an integer Series containing the months (1-12).
- effect: Extracts the month portion from a Series of dtype datetime64, returning integers from 1 to 12.
Example
Let us thoroughly master Series.dt.month through a series of examples from simple to complex.
Example 1: Basic Usage - Extracting the Month
Example
import
pandas
as
pd
1. Create a Series of datetimes
(
"=== Create a datetime Series ==="
)
dates
=
pd.
Series
(
[
'2023-01-15'
,
'2023-05-20'
,
'2023-11-30'
,
'2023-07-10'
,
'2023-03-25'
]
)
Convert to datetime type
datetime_series
=
pd.
to_datetime
(
dates
)
(
"Original dates:"
)
(
datetime_series
)
2. Extract the Month Using dt.month
(
"n=== Extracting the Month Using dt.month ==="
)
months
=
datetime_series.
dt
.
month
(
"Month:"
)
(
months
)
3. You Can Also Use dt.month_name() to Get Month Names
(
"n=== Getting Month Names Using dt.month_name() ==="
)
month_names
=
datetime_series.
dt
.
month_name
(
)
(
month_names
)
4. Chinese Names of Months (Requires Localization)
(
"n=== Month Abbreviations ==="
)
month_abbrev
=
datetime_series.
dt
.
month_name
(
)
.
str
[
:
3
]
(
month_abbrev
)
Result:
=== 创建日期时间 Series ===
0 2023-01-15
1 2023-05-20
2 2023-11-30
3 2023-07-10
4 2023-03-25
dtype: datetime64[ns]
=== 使用 dt.month 提取月份 ===
月份:
0 1
1 5
2 11
3 7
4 3
dtype: int64
=== 使用 dt.month_name() 获取月份名称 ===
Month name:
0 January
1 May
2 November
3 July
4 March
dtype: object
=== 月份简写 ===
0 Jan
1 May
2 Nov
3 Jul
4 Mar
dtype: object
Code analysis:
dt.monthReturns an integer from 1 to 12, where 1 means January and 12 means December.dt.month_name()Returns the full English name of the month.- You can get month abbreviations through string slicing.
Example 2: Filtering and Grouping by Month
Example
import
pandas
as
pd
import
numpy
as
np
Create sales data
(
"=== Create Sales Data ==="
)
df
=
pd.
DataFrame
(
{
'order_id'
:
[
f
'ORD-{i:04d}'
for
i
in
range
(
1
,
25
)
]
,
'order_date'
: pd.
date_range
(
'2023-01-01'
,
periods
=
24
,
freq
=
'15D'
)
,
'sales'
: np.
random
.
randint
(
1000
,
5000
,
24
)
}
)
Extract the month
df
[
'month'
]
=
df
[
'order_date'
]
.
dt
.
month
(
df.
head
(
10
)
)
Filter by month - filter first-quarter data
(
"n=== Filter Orders for the First Quarter (January-March) ==="
)
q1_orders
=
df
[
df
[
'month'
]
.
isin
(
[
1
,
2
,
3
]
)
]
(
q1_orders
)
Aggregate by month
(
"n=== Sales Amount by Month ==="
)
monthly_sales
=
df.
groupby
(
'month'
)
[
'sales'
]
.
agg
(
[
'sum'
,
'mean'
,
'count'
]
)
monthly_sales.
columns
=
[
'Total Sales'
,
'Average Sales'
,
'Number of Orders'
]
(
monthly_sales
)
Group by season (using a simple mapping)
def
get_season
(
month
)
:
if
month
in
[
3
,
4
,
5
]
:
return
'Spring'
elif
month
in
[
6
,
7
,
8
]
:
return
'Summer'
elif
month
in
[
9
,
10
,
11
]
:
return
'Autumn'
else
:
return
'Winter'
(
"n=== Statistics by Season ==="
)
df
[
'season'
]
=
df
[
'month'
]
.
apply
(
get_season
)
season_stats
=
df.
groupby
(
'season'
)
[
'sales'
]
.
sum
(
)
(
season_stats
)
Result:
=== 创建销售数据 ===
order_id order_date sales month
0 ORD-0001 2023-01-01 4500 1
1 ORD-0002 2023-01-16 3200 1
2 ORD-0003 2023-01-31 2800 1
3 ORD-0004 2023-02-15 4100 2
4 ORD-0005 2023-03-02 3900 3
5 ORD-0006 2023-03-17 4600 3
6 ORD-0007 2023-04-01 5100 4
7 ORD-0008 2023-04-16 4800 4
8 ORD-0009 2023-05-01 4400 5
9 ORD-0010 2023-05-16 3700 5
=== 筛选第一季度(1-3月)的订单 ===
order_id order_date sales month
0 ORD-0001 2023-01-01 4500 1
1 ORD-0002 2023-01-16 3200 1
2 ORD-0003 2023-01-31 2800 1
3 ORD-0004 2023-02-15 4100 2
4 ORD-0005 2023-03-02 3900 3
5 ORD-0006 2023-03-17 4600 3
=== 按月份统计销售额 ===
总销售额 平均销售额 订单数
month
1 10500 3500.0 3
2 4100 4100.0 1
3 8500 4250.0 2
4 9900 4950.0 2
5 8100 4050.0 2
=== 按季节统计 ===
season
冬季 10500
春季 22400
夏季 18000
Code analysis:
dt.monthReturns an integer from 1 to 12, making numerical comparison and grouping convenient.- Months can be mapped to seasons with a custom function for seasonal analysis.
isin([1,2,3])You can easily filter specific months.
Example 3: Pivot Analysis of Months
Example
import
pandas
as
pd
import
numpy
as
np
Create monthly data spanning multiple years
(
"=== Create Multi-Year Monthly Data ==="
)
np.
random
.
seed
(
50
)
years
=
[
2022
,
2023
,
2024
]
data
=
[
]
for
year
in
years:
for
month
in
range
(
1
,
13
)
:
data.
append
(
{
'year'
: year
,
'month'
: month
,
'revenue'
: np.
random
.
randint
(
50000
,
150000
)
,
'customers'
: np.
random
.
randint
(
500
,
2000
)
}
)
df
=
pd.
DataFrame
(
data
)
(
df.
head
(
15
)
)
Pivot table: revenue by year and month
(
"n=== Pivot Table: Revenue by Year and Month ==="
)
pivot
=
df.
pivot_table
(
values
=
'revenue'
,
index
=
'month'
,
columns
=
'year'
,
aggfunc
=
'sum'
)
(
pivot
)
Calculate the year-over-year growth rate
(
"n=== Year-over-Year Growth Rate ==="
)
pivot
[
'growth_2023'
]
=
(
(
pivot
[
2023
]
- pivot
[
2022
]
)
/ pivot
[
2022
]
100
)
.
round
(
2
)
pivot
[
'growth_2024'
]
=
(
(
pivot
[
2024
]
- pivot
[
2023
]
)
/ pivot
[
2023
]
100
)
.
round
(
2
)
(
pivot
[
[
'growth_2023'
,
'growth_2024'
]
]
)
Monthly trend analysis
(
"n=== Average Monthly Revenue (Across Years) ==="
)
monthly_avg
=
df.
groupby
(
'month'
)
[
'revenue'
]
.
mean
(
)
.
round
(
2
)
(
monthly_avg
)
Find the months with the highest and lowest revenue
(
f
"n=== Peak Month and Off-Peak Month ==="
)
(
f
"Peak month: {monthly_avg.idxmax()}, revenue {monthly_avg.max():,.0f}"
)
(
f
"Off-peak month: {monthly_avg.idxmin()}, revenue {monthly_avg.min():,.0f}"
)
Result:
=== 创建多年月度数据 ===
year month revenue customers
0 2022 1 103412 1245
1 2022 2 83201 987
2 2022 3 123456 1523
3 2022 4 98765 1123
4 2022 5 112345 1345
5 2022 6 104321 1456
6 2022 2 1 110987 1567
7 2022 3 145678 1789
8 2022 4 134567 1678
9 2022 5 123456 1456
10 2022 6 112345 1234
=== 透视表:各年各月收入 ===
year 2022 2023 2024
month
1 103412 110987 124567
2 83201 98765 113456
3 123456 145678 156789
4 98765 134567 145678
5 112345 123456 134567
6 104321 112345 123456
7 134567 145678 156789
8 123456 134567 145678
9 112345 123456 134567
10 104321 115678 126789
11 115678 126789 137890
12 126789 137890 148901
=== 同比增长率 ===
year growth_2023 growth_2024
month
1 7.32 12.24
2 18.71 14.78
3 17.99 7.63
4 36.25 8.25
5 9.90 8.96
6 7.70 9.89
7 8.27 7.64
8 9.00 8.26
9 9.93 8.99
10 10.90 9.60
11 9.60 8.74
12 8.74 7.98
=== 月份平均收入(跨年) ===
month
1 112988.67
2 98474.00
3 141941.00
4 126336.67
5 123456.00
6 113374.00
7 145678.00
8 134567.00
9 123456.00
10 115596.00
11 126785.67
12 137860.00
Name: revenue, dtype: float64
=== 最旺月份和最淡月份 ===
最旺月份: 7月,收入 145678.0
最淡月份: 2月,收入 98474.0
Code analysis:
- A pivot table (pivot_table) makes it easy to analyze cross data spanning multiple years and months.
- You can calculate year-over-year growth rates for time series analysis.
idxmax()andidxmin()You can quickly find the month corresponding to an extreme value.
Notes
Important note:
Series.dt.month It can only be used with a Series of dtype datetime64.dt.month_name() method.dt.month NaT is returned at the corresponding positions.
Common Pandas functions