Pandas Series.dt.year 属性
Series.dt.yearPandas で使用される日時から年を抽出する属性です。これは dt アクセサの一部であり、datetime 型の Series から年情報をすばやく抽出できます。
時系列データ分析では、年ごとにグループ化、フィルタリング、または集計操作を行う必要がよくあります。dt.yearこの属性により、こうした操作が簡単かつ効率的になります。
単語の意味: year「年」を意味し、日付の中の年の部分を返します。
基本構文とパラメータ
Series.dt.yearSeries の dt アクセサの属性であり、年の抽出に使用されます。
構文形式
Series.dt.year
パラメータの説明
この属性はパラメータを一切必要とせず、datetime Series の年情報に直接アクセスします。
戻り値の説明
- 戻り値:年を含む整数型の Series を返します。
- 効果:datetime64 型の Series から年の部分を抽出し、4桁の整数を返します。
実例
簡単なものから複雑なものまでの一連の例を通じて、Series.dt.yearの使い方を徹底的に習得しましょう。
例1:基本的な使い方 - 年の抽出
実例
import pandas as pd
# 1. 日時 Series を作成
print("=== 日時 Series を作成 ===")
dates = pd.Series([
'2023-01-15',
'2023-05-20',
'2022-11-30',
'2021-07-10',
'2024-03-25'
])
# datetime 型に変換
datetime_series = pd.to_datetime(dates)
print("元の日付:")
print(datetime_series)
# 2. dt.year で年を抽出
print("n=== dt.year で年を抽出 ===")
years = datetime_series.dt.year
print("年:")
print(years)
print(f"型: {years.dtype}")
# 3. datetime Series から直接アクセス
print("n=== 直接チェーン呼び出し ===")
years_direct = pd.to_datetime(dates).dt.year
print(years_direct)
# 1. 日時 Series を作成
print("=== 日時 Series を作成 ===")
dates = pd.Series([
'2023-01-15',
'2023-05-20',
'2022-11-30',
'2021-07-10',
'2024-03-25'
])
# datetime 型に変換
datetime_series = pd.to_datetime(dates)
print("元の日付:")
print(datetime_series)
# 2. dt.year で年を抽出
print("n=== dt.year で年を抽出 ===")
years = datetime_series.dt.year
print("年:")
print(years)
print(f"型: {years.dtype}")
# 3. datetime Series から直接アクセス
print("n=== 直接チェーン呼び出し ===")
years_direct = pd.to_datetime(dates).dt.year
print(years_direct)
実行結果:
=== 创建日期时间 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
コードの解説:
- まず Series を datetime64 型に変換する必要があります。その後、dt アクセサを使用できます。
dt.year返されるのは整数型の Series で、各行が元の日付の年に対応します。- チェーン呼び出しが可能で、変換と抽出を一度に行えます。
例2:年ごとにデータをフィルタリング
実例
import pandas as pd
import numpy as np
# 販売データを作成
print("=== 販売データの例 ===")
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)
# 年を抽出
print("n=== 年の列を追加 ===")
df['year'] = df['order_date'].dt.year
print(df)
# 年ごとにフィルタリング
print("n=== 2023 年の注文をフィルタリング ===")
orders_2023 = df[df['year'] == 2023]
print(orders_2023)
# 年ごとにグループ化して集計
print("n=== 年ごとに売上を集計 ===")
yearly_sales = df.groupby('year')['sales'].sum()
print(yearly_sales)
# 複数の年でフィルタリング
print("n=== 2022 年と 2024 年の注文をフィルタリング ===")
selected_years = df[df['year'].isin([2022, 2024])]
print(selected_years)
import numpy as np
# 販売データを作成
print("=== 販売データの例 ===")
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)
# 年を抽出
print("n=== 年の列を追加 ===")
df['year'] = df['order_date'].dt.year
print(df)
# 年ごとにフィルタリング
print("n=== 2023 年の注文をフィルタリング ===")
orders_2023 = df[df['year'] == 2023]
print(orders_2023)
# 年ごとにグループ化して集計
print("n=== 年ごとに売上を集計 ===")
yearly_sales = df.groupby('year')['sales'].sum()
print(yearly_sales)
# 複数の年でフィルタリング
print("n=== 2022 年と 2024 年の注文をフィルタリング ===")
selected_years = df[df['year'].isin([2022, 2024])]
print(selected_years)
実行結果:
=== 销售数据示例 ===
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
コードの解説:
- 年を抽出すると、通常の数値列と同じようにフィルタリング、グループ化などの操作ができます。
isin()複数の年をフィルタリングできます。- 比較演算子(>、=、<=)を使用した範囲フィルタリングをサポートします。
例3:年に関する分析
実例
import pandas as pd
import numpy as np
# より複雑なデータセットを作成
print("=== 複数年のデータを含むデータセットを作成 ===")
np.random.seed(42)
# 5年分のデータを生成
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))
})
# 年を抽出
df['year'] = df['date'].dt.year
print(f"データセットのサイズ: {len(df)} 件のレコード")
print(f"年の範囲: {df['year'].min()} - {df['year'].max()}")
# 年ごとに集計
print("n=== 年ごとの集計 ===")
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)
# 年・月ごとのデータ量
print("n=== 年・月ごとのレコード数 ===")
df['month'] = df['date'].dt.month
monthly_counts = df.groupby(['year', 'month']).size().unstack(fill_value=0)
print(monthly_counts)
import numpy as np
# より複雑なデータセットを作成
print("=== 複数年のデータを含むデータセットを作成 ===")
np.random.seed(42)
# 5年分のデータを生成
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))
})
# 年を抽出
df['year'] = df['date'].dt.year
print(f"データセットのサイズ: {len(df)} 件のレコード")
print(f"年の範囲: {df['year'].min()} - {df['year'].max()}")
# 年ごとに集計
print("n=== 年ごとの集計 ===")
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)
# 年・月ごとのデータ量
print("n=== 年・月ごとのレコード数 ===")
df['month'] = df['date'].dt.month
monthly_counts = df.groupby(['year', 'month']).size().unstack(fill_value=0)
print(monthly_counts)
実行結果:
=== 创建包含多年数据的数据集 ===
数据集大小: 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
コードの解説:
- を通じて
groupby().agg()年ごとに多次元の集計を行うことができます。 groupby(['year', 'month']).size().unstack()年と月のクロス集計表を作成できます。- 2024 年のデータが 102 件のみなのは、データが 2024 年 4 月(現在日付の前)まで生成されているためです。
注意事項
重要な注意:
Series.dt.yeardatetime64 型の Series にのみ使用できます。- Series が datetime 型でない場合は、まず
pd.to_datetime()変換する必要があります。- 抽出された年は 4 桁の整数で、数値演算や比較に直接使用できます。
- 欠損値(NaT)を含むデータを処理する場合、
dt.year対応する位置に NaT が返されます。
その他の拡張
Pandas 常用関数