Pandas Series.dt.year Attribute
Series.dt.year is a Pandas attribute used toextracts the year from a datetimeIt is part of the dt accessor and can quickly extract year information from a Series of datetime type.
In time series data analysis, it is often necessary to group, filter, or aggregate by year.dt.year attribute makes such operations simple and efficient.
Word meaning: year means "year", that is, it returns the year portion of a date.
Basic syntax and parameters
Series.dt.year It is an attribute of the dt accessor of Series, used to extract the year.
Syntax format
Series.dt.year
Parameter Description
This attribute requires no arguments; simply access the year information of a datetime Series.
Return value description
- Return Value: Returns an integer Series containing the years.
- effect: Extracts the year portion from a Series of dtype datetime64, returning a 4-digit integer.
Example
Let us thoroughly master Series.dt.year through a series of examples from simple to complex.
Example 1: Basic Usage - Extracting the Year
Example
import
pandas
as
pd
1. Create a Series of datetimes
(
"=== Create a datetime Series ==="
)
dates
=
pd.
Series
(
[
'2023-01-15'
,
'2023-05-20'
,
'2022-11-30'
,
'2021-07-10'
,
'2024-03-25'
]
)
Convert to datetime type
datetime_series
=
pd.
to_datetime
(
dates
)
(
"Original dates:"
)
(
datetime_series
)
2. Extract the Year Using dt.year
(
"n=== Extracting the Year Using dt.year ==="
)
years
=
datetime_series.
dt
.
year
(
"Year:"
)
(
years
)
(
f
"dtype: {years.dtype}"
)
3. Access Directly from a datetime Series
(
"n=== Direct Chained Call ==="
)
years_direct
=
pd.
to_datetime
(
dates
)
.
dt
.
year
(
years_direct
)
Result:
=== 创建日期时间 Series ===
0 2023-01-15
1 2023-05-20
2 2022-11-30
3 2021-07-10
4 2024-03-25
dtype: datetime64[ns]
=== 使用 dt.year 提取年份 ===
年份:
0 2023
1 2023
2 2022
3 2021
4 2024
dtype: int64
=== 直接链式调用 ===
0 2023
1 2023
2 2022
3 2021
4 2024
dtype: int64
Code analysis:
- You must first convert the Series to dtype datetime64 before using the dt accessor.
dt.yearThe return value is an integer Series, with each row corresponding to the year of the original date.- You can chain calls to convert and extract in one step.
Example 2: Filtering Data by Year
Example
import
pandas
as
pd
import
numpy
as
np
Create sales data
(
"=== Sales Data Example ==="
)
df
=
pd.
DataFrame
(
{
'order_id'
:
[
f
'ORD-{i:04d}'
for
i
in
range
(
1
,
11
)
]
,
'order_date'
: pd.
date_range
(
'2022-01-01'
,
periods
=
10
,
freq
=
'MS'
)
,
'sales'
:
[
1200
,
1500
,
1800
,
2100
,
1900
,
2300
,
2500
,
2800
,
3100
,
3500
]
}
)
(
df
)
Extract the year
(
"n=== Add a Year Column ==="
)
df
[
'year'
]
=
df
[
'order_date'
]
.
dt
.
year
(
df
)
Filter by year
(
"n=== Filter Orders from 2023 ==="
)
orders_2023
=
df
[
df
[
'year'
]
==
2023
]
(
orders_2023
)
Aggregate by year
(
"n=== Sales Amount by Year ==="
)
yearly_sales
=
df.
groupby
(
'year'
)
[
'sales'
]
.
sum
(
)
(
yearly_sales
)
Filter multiple years
(
"n=== Filter Orders from 2022 and 2024 ==="
)
selected_years
=
df
[
df
[
'year'
]
.
isin
(
[
2022
,
2024
]
)
]
(
selected_years
)
Result:
=== 销售数据示例 ===
order_id order_date sales
0 ORD-0001 2022-01-01 1200
1 ORD-0002 2022-02-01 1500
2 ORD-0003 2022-03-01 1800
3 ORD-0004 2022-04-01 2100
4 ORD-0005 2022-05-01 1900
5 ORD-0006 2022-06-01 2300
6 ORD-0007 2022-07-01 2500
7 ORD-0008 2022-08-01 2800
8 ORD-0009 2022-09-01 3100
9 ORD-0010 2022-10-01 3500
=== 添加年份列 ===
order_id order_date sales year
0 ORD-0001 2022-01-01 1200 2022
1 ORD-0002 2022-02-01 1500 2022
2 ORD-0003 2022-03-01 1800 2022
3 ORD-0004 2022-04-01 2100 2022
4 ORD-0005 2022-05-01 1900 2022
5 ORD-0006 2022-06-01 2300 2022
6 ORD-0007 2022-07-01 2500 2022
7 ORD-0008 2022-08-01 2800 2022
8 ORD-0009 2022-09-01 3100 2022
9 ORD-0010 2022-10-01 3500 2022
=== 筛选 2023 年的订单 ===
Empty DataFrame
Columns: [order_id, order_date, sales, year]
Index: []
=== 按年份统计销售额 ===
year
2022 22900
Name: sales, dtype: int64
=== 筛选 2022 和 2024 年的订单 ===
order_id order_date sales year
0 ORD-0001 2022-01-01 1200 2022
1 ORD-0002 2022-02-01 1500 2022
2 ORD-0003 2022-03-01 1800 2022
3 ORD-0004 2022-04-01 2100 2022
4 ORD-0005 2022-05-01 1900 2022
5 ORD-0006 2022-06-01 2300 2022
6 ORD-0007 2022-07-01 2500 2022
7 ORD-0008 2022-08-01 2800 2022
8 ORD-0009 2022-09-01 3100 2022
9 ORD-0010 2022-10-01 3500 2022
Code analysis:
- Once extracted, the year can be filtered, grouped, and manipulated like an ordinary numeric column.
isin()You can filter multiple years.- Supports comparison operators (>, >=,<=) for range filtering.
Example 3: Year-Related Analysis
Example
import
pandas
as
pd
import
numpy
as
np
Create a More Complex Dataset
(
"=== Create a Dataset Spanning Multiple Years ==="
)
np.
random
.
seed
(
42
)
Generate 5 years of data
dates
=
pd.
date_range
(
'2020-01-01'
,
'2024-12-31'
,
freq
=
'D'
)
df
=
pd.
DataFrame
(
{
'date'
: dates
,
'temperature'
: np.
random
.
uniform
(
10
,
35
,
len
(
dates
)
)
,
'sales'
: np.
random
.
randint
(
100
,
500
,
len
(
dates
)
)
}
)
Extract the year
df
[
'year'
]
=
df
[
'date'
]
.
dt
.
year
(
f
"Dataset size: {len(df)} records"
)
(
f
"Year range: {df['year'].min()} - {df['year'].max()}"
)
Statistics by year
(
"n=== Statistics by Year ==="
)
yearly_stats
=
df.
groupby
(
'year'
)
.
agg
(
{
'temperature'
:
[
'mean'
,
'min'
,
'max'
]
,
'sales'
:
[
'sum'
,
'mean'
,
'count'
]
}
)
.
round
(
2
)
yearly_stats.
columns
=
[
'_'
.
join
(
col
)
.
strip
(
)
for
col
in
yearly_stats.
columns
.
values
]
(
yearly_stats
)
Data volume by year and month
(
"n=== Number of Records by Year and Month ==="
)
df
[
'month'
]
=
df
[
'date'
]
.
dt
.
month
monthly_counts
=
df.
groupby
(
[
'year'
,
'month'
]
)
.
size
(
)
.
unstack
(
fill_value
=
0
)
(
monthly_counts
)
Result:
=== 创建包含多年数据的数据集 ===
数据集大小: 1826 条记录
年份范围: 2020 - 2024
=== 按年份统计 ===
temperature_mean temperature_min temperature_max sales_sum sales_mean sales_count
year
2020 22.47 10.06 34.74 98500 266.31 366
2021 22.56 10.08 34.83 99500 272.60 365
2022 22.43 10.01 34.90 100100 274.11 365
2023 22.53 10.00 34.95 100600 275.62 365
2024 15.90 10.03 34.83 27500 268.93 102
=== 各年各月记录数 ===
month 1 2 3 4 5 6 7 8 9 10 11 12
year
2020 31 29 31 30 31 30 31 31 30 31 30 31
2021 31 28 31 30 31 30 31 31 30 31 30 31
2022 31 28 31 30 31 30 31 31 30 31 30 31
2023 31 28 31 30 31 30 31 31 30 31 30 31
2024 31 29 31 30 31 30 31 31 30 31 30 31
Code analysis:
- Pass
groupby().agg()You can perform multi-dimensional statistics by year. groupby(['year', 'month']).size().unstack()You can create a cross-tabulation of year and month.- There are only 102 records for 2024 because data was generated up to April 2024 (before the current date).
Notes
Important note:
Series.dt.year It can only be used with a Series of dtype datetime64.pd.to_datetime() to convert.dt.year NaT is returned at the corresponding positions.
Common Pandas functions