Pandas Series.dt.month 属性
Series.dt.monthはPandasで日時の月を抽出するための属性です。これは dt アクセサの一部であり、datetime 型の Series から月情報(1〜12)をすばやく抽出できます。
時系列データ分析では、月ごとの分析は一般的なニーズであり、例えば月次レポート、季節性分析などがあります。dt.monthこの属性により、このような操作が簡単かつ効率的になります。
単語の意味: month「月」という意味で、日付の月の部分(1〜12)を返します。
基本構文とパラメータ
Series.dt.monthは Series の dt アクセサの属性であり、月の抽出に使用されます。
構文形式
Series.dt.month
パラメータの説明
この属性はパラメータを必要とせず、datetime Series の月情報に直接アクセスします。
戻り値の説明
- 戻り値:月を含む整数の Series(1〜12)を返します。
- 効果:datetime64 型の Series から月の部分を抽出し、1 から 12 の整数を返します。
例
簡単なものから複雑なものまでの一連の例を通じて、徹底的にSeries.dt.monthの使い方を習得しましょう。
例1:基本用法 - 月の抽出
例
import pandas as pd
# 1. 日時 Series を作成
print("=== 日時 Series を作成 ===")
dates = pd.Series([
'2023-01-15',
'2023-05-20',
'2023-11-30',
'2023-07-10',
'2023-03-25'
])
# datetime 型に変換
datetime_series = pd.to_datetime(dates)
print("元の日付:")
print(datetime_series)
# 2. dt.month で月を抽出
print("n=== dt.month で月を抽出 ===")
months = datetime_series.dt.month
print("月:")
print(months)
# 3. dt.month_name() で月名を取得することもできます
print("n=== dt.month_name() で月名を取得 ===")
month_names = datetime_series.dt.month_name()
print(month_names)
# 4. 月の中国語名(ローカライズが必要)
print("n=== 月の略称 ===")
month_abbrev = datetime_series.dt.month_name().str[:3]
print(month_abbrev)
# 1. 日時 Series を作成
print("=== 日時 Series を作成 ===")
dates = pd.Series([
'2023-01-15',
'2023-05-20',
'2023-11-30',
'2023-07-10',
'2023-03-25'
])
# datetime 型に変換
datetime_series = pd.to_datetime(dates)
print("元の日付:")
print(datetime_series)
# 2. dt.month で月を抽出
print("n=== dt.month で月を抽出 ===")
months = datetime_series.dt.month
print("月:")
print(months)
# 3. dt.month_name() で月名を取得することもできます
print("n=== dt.month_name() で月名を取得 ===")
month_names = datetime_series.dt.month_name()
print(month_names)
# 4. 月の中国語名(ローカライズが必要)
print("n=== 月の略称 ===")
month_abbrev = datetime_series.dt.month_name().str[:3]
print(month_abbrev)
実行結果:
=== 创建日期时间 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() 获取月份名称 === 月份名称: 0 January 1 May 2 November 3 July 4 March dtype: object === 月份简写 === 0 Jan 1 May 2 Nov 3 Jul 4 Mar dtype: object
コード解説:
dt.month1〜12 の整数を返します。1 は 1月、12 は 12月を表します。dt.month_name()月の英語の正式名称を返します。- 文字列スライスを使用して月の略称を取得できます。
例2:月ごとのフィルタリングとグループ化
例
import pandas as pd
import numpy as np
# 売上データを作成
print("=== 売上データを作成 ===")
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)
})
# 月を抽出
df['month'] = df['order_date'].dt.month
print(df.head(10))
# 月でフィルタリング - 第1四半期のデータを抽出
print("n=== 第1四半期(1〜3月)の注文を抽出 ===")
q1_orders = df[df['month'].isin([1, 2, 3])]
print(q1_orders)
# 月ごとにグループ化して集計
print("n=== 月ごとの売上額を集計 ===")
monthly_sales = df.groupby('month')['sales'].agg(['sum', 'mean', 'count'])
monthly_sales.columns = ['総売上額', '平均売上額', '注文数']
print(monthly_sales)
# 季節ごとにグループ化(単純なマッピングを使用)
def get_season(month):
if month in [3, 4, 5]:
return '春'
elif month in [6, 7, 8]:
return '夏'
elif month in [9, 10, 11]:
return '秋'
else:
return '冬'
print("n=== 季節ごとに集計 ===")
df['season'] = df['month'].apply(get_season)
season_stats = df.groupby('season')['sales'].sum()
print(season_stats)
import numpy as np
# 売上データを作成
print("=== 売上データを作成 ===")
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)
})
# 月を抽出
df['month'] = df['order_date'].dt.month
print(df.head(10))
# 月でフィルタリング - 第1四半期のデータを抽出
print("n=== 第1四半期(1〜3月)の注文を抽出 ===")
q1_orders = df[df['month'].isin([1, 2, 3])]
print(q1_orders)
# 月ごとにグループ化して集計
print("n=== 月ごとの売上額を集計 ===")
monthly_sales = df.groupby('month')['sales'].agg(['sum', 'mean', 'count'])
monthly_sales.columns = ['総売上額', '平均売上額', '注文数']
print(monthly_sales)
# 季節ごとにグループ化(単純なマッピングを使用)
def get_season(month):
if month in [3, 4, 5]:
return '春'
elif month in [6, 7, 8]:
return '夏'
elif month in [9, 10, 11]:
return '秋'
else:
return '冬'
print("n=== 季節ごとに集計 ===")
df['season'] = df['month'].apply(get_season)
season_stats = df.groupby('season')['sales'].sum()
print(season_stats)
実行結果:
=== 创建销售数据 ===
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
コード解説:
dt.month1〜12 の整数を返すため、数値の比較やグループ化が容易です。- 月はカスタム関数と組み合わせて季節にマッピングでき、季節性分析に使用できます。
isin([1,2,3])特定の月を簡単にフィルタリングできます。
例3:月のピボット分析
例
import pandas as pd
import numpy as np
# 複数年の月次データを作成
print("=== 複数年の月次データを作成 ===")
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)
print(df.head(15))
# ピボットテーブル:年別・月別の収入
print("n=== ピボットテーブル:年別・月別の収入 ===")
pivot = df.pivot_table(
values='revenue',
index='month',
columns='year',
aggfunc='sum'
)
print(pivot)
# 前年同期比成長率を計算
print("n=== 前年同期比成長率 ===")
pivot['growth_2023'] = ((pivot[2023] - pivot[2022]) / pivot[2022] * 100).round(2)
pivot['growth_2024'] = ((pivot[2024] - pivot[2023]) / pivot[2023] * 100).round(2)
print(pivot[['growth_2023', 'growth_2024']])
# 月のトレンド分析
print("n=== 月の平均収入(年をまたぐ) ===")
monthly_avg = df.groupby('month')['revenue'].mean().round(2)
print(monthly_avg)
# 収入が最も高い月と低い月を特定
print(f"n=== 最も好調な月と最も低迷した月 ===")
print(f"最も好調な月: {monthly_avg.idxmax()}月、収入 {monthly_avg.max():,.0f}")
print(f"最も低迷した月: {monthly_avg.idxmin()}月、収入 {monthly_avg.min():,.0f}")
import numpy as np
# 複数年の月次データを作成
print("=== 複数年の月次データを作成 ===")
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)
print(df.head(15))
# ピボットテーブル:年別・月別の収入
print("n=== ピボットテーブル:年別・月別の収入 ===")
pivot = df.pivot_table(
values='revenue',
index='month',
columns='year',
aggfunc='sum'
)
print(pivot)
# 前年同期比成長率を計算
print("n=== 前年同期比成長率 ===")
pivot['growth_2023'] = ((pivot[2023] - pivot[2022]) / pivot[2022] * 100).round(2)
pivot['growth_2024'] = ((pivot[2024] - pivot[2023]) / pivot[2023] * 100).round(2)
print(pivot[['growth_2023', 'growth_2024']])
# 月のトレンド分析
print("n=== 月の平均収入(年をまたぐ) ===")
monthly_avg = df.groupby('month')['revenue'].mean().round(2)
print(monthly_avg)
# 収入が最も高い月と低い月を特定
print(f"n=== 最も好調な月と最も低迷した月 ===")
print(f"最も好調な月: {monthly_avg.idxmax()}月、収入 {monthly_avg.max():,.0f}")
print(f"最も低迷した月: {monthly_avg.idxmin()}月、収入 {monthly_avg.min():,.0f}")
実行結果:
=== 创建多年月度数据 === 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
コード解説:
- ピボットテーブル(pivot_table)を使用すると、複数年にわたる月別のクロスデータを簡単に分析できます。
- 前年同期比成長率を計算して時系列分析を行うことができます。
idxmax()とidxmin()最大値・最小値に対応する月をすばやく見つけることができます。
注意事項
重要な注意:
Series.dt.monthdatetime64 型の Series にのみ使用できます。- 返される月の範囲は 1〜12 で、1 は 1月、12 は 12月を表します。
- 月名が必要な場合は、
dt.month_name()メソッドを使用します。- 欠損値(NaT)を含むデータを処理する場合、
dt.month対応する位置の NaT が返されます。
その他の拡張
Pandas よく使う関数