Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Series.dt.year Attribute

Pandas Series.dt.year Attribute

Pandas Universal Functions Common Pandas functions


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


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

print

(

"=== 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

)

print

(

"Original dates:"

)

print

(

datetime_series

)

2. Extract the Year Using dt.year

print

(

"n=== Extracting the Year Using dt.year ==="

)

years

=

datetime_series.

dt

.

year

print

(

"Year:"

)

print

(

years

)

print

(

f

"dtype: {years.dtype}"

)

3. Access Directly from a datetime Series

print

(

"n=== Direct Chained Call ==="

)

years_direct

=

pd.

to_datetime

(

dates

)

.

dt

.

year

print

(

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:

  1. You must first convert the Series to dtype datetime64 before using the dt accessor.
  2. dt.year The return value is an integer Series, with each row corresponding to the year of the original date.
  3. 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

print

(

"=== 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

]

}

)

print

(

df

)

Extract the year

print

(

"n=== Add a Year Column ==="

)

df

[

'year'

]

=

df

[

'order_date'

]

.

dt

.

year

print

(

df

)

Filter by year

print

(

"n=== Filter Orders from 2023 ==="

)

orders_2023

=

df

[

df

[

'year'

]

==

2023

]

print

(

orders_2023

)

Aggregate by year

print

(

"n=== Sales Amount by Year ==="

)

yearly_sales

=

df.

groupby

(

'year'

)

[

'sales'

]

.

sum

(

)

print

(

yearly_sales

)

Filter multiple years

print

(

"n=== Filter Orders from 2022 and 2024 ==="

)

selected_years

=

df

[

df

[

'year'

]

.

isin

(

[

2022

,

2024

]

)

]

print

(

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:

Example 3: Year-Related Analysis

Example

import

pandas

as

pd

import

numpy

as

np

Create a More Complex Dataset

print

(

"=== 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

print

(

f

"Dataset size: {len(df)} records"

)

print

(

f

"Year range: {df['year'].min()} - {df['year'].max()}"

)

Statistics by year

print

(

"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

]

print

(

yearly_stats

)

Data volume by year and month

print

(

"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

)

print

(

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:

Notes

Important note:

  • Series.dt.year It can only be used with a Series of dtype datetime64.
  • If the Series is not of datetime type, you need to first use pd.to_datetime() to convert.
  • The extracted year is a 4-digit integer that can be used directly in numerical operations and comparisons.
  • When working with data containing missing values (NaT),dt.year NaT is returned at the corresponding positions.

  • Pandas Common Functions Common Pandas functions