Pandas Series.dt.month Property

Pandas 通用函数Pandas Common Functions


Series.dt.monthis the property in Pandas used toextract the month from date-times.It 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.monthThis property makes such operations simple and efficient.

Word Meaning: monthMeans "month", i.e., it returns the month part of the date (1 to 12).


Basic Syntax and Parameters

Series.dt.monthIt is a property of the Series dt accessor, used to extract the month.

Syntax Format

Series.dt.month

Parameter Description

This property does not require any parameters; it directly accesses the month information of the datetime Series.

Return Value Description

  • Return value: Returns an integer Series (1-12) containing the month.
  • Effect: Extracts the month part from a datetime64 Series, returning integers from 1 to 12.

Examples

Let's thoroughly master, through a series of examples from simple to complex,Series.dt.monththe usage of it.

Example 1: Basic Usage - Extract Month

Example

import pandas as pd

# 1. Create a datetime Series
print("=== Create 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)
print("Original dates:")
print(datetime_series)

# 2. Use dt.month to extract the month
print("n=== Use dt.month to extract the month ===")
months = datetime_series.dt.month
print("Month:")
print(months)

# 3. You can also use dt.month_name() to get the month name
print("n=== Use dt.month_name() to get month names ===")
month_names = datetime_series.dt.month_name()
print(month_names)

# 4. Chinese names of months (requires localization)
print("n=== Month abbreviations ===")
month_abbrev = datetime_series.dt.month_name().str[:3]
print(month_abbrev)

Output:

=== 创建日期时间 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

Code explanation:

  1. dt.monthReturns integers from 1-12, where 1 represents January and 12 represents December.
  2. dt.month_name()Returns the full English name of the month.
  3. Month abbreviations can be obtained via string slicing.

Example 2: Filtering and Grouping by Month

Example

import pandas as pd
import numpy as np

# Create sales data
print("=== 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 month
df['month'] = df['order_date'].dt.month
print(df.head(10))

# Filter by month - filter Q1 data
print("n=== Filter orders for Q1 (Jan-Mar) ===")
q1_orders = df[df['month'].isin([1, 2, 3])]
print(q1_orders)

# Group by month and aggregate
print("n=== Sales statistics by month ===")
monthly_sales = df.groupby('month')['sales'].agg(['sum', 'mean', 'count'])
monthly_sales.columns = ['Total sales', 'Average sales', 'Order count']
print(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'

print("n=== Statistics by season ===")
df['season'] = df['month'].apply(get_season)
season_stats = df.groupby('season')['sales'].sum()
print(season_stats)

Output:

=== 创建销售数据 ===
     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 explanation:

  • dt.monthReturns integers from 1-12, making it easy to perform numerical comparison and grouping.
  • Months can be mapped to seasons with custom functions for seasonal analysis.
  • isin([1,2,3])Makes it convenient to filter specific months.

Example 3: Month Pivot Analysis

Example

import pandas as pd
import numpy as np

# Create multi-year monthly data
print("=== 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)
print(df.head(15))

# Pivot table: revenue by year and month
print("n=== Pivot table: revenue by year and month ===")
pivot = df.pivot_table(
    values='revenue',
    index='month',
    columns='year',
    aggfunc='sum'
)
print(pivot)

# Calculate year-over-year growth rate
print("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)
print(pivot[['growth_2023', 'growth_2024']])

# Month trend analysis
print("n=== Average monthly revenue (across years) ===")
monthly_avg = df.groupby('month')['revenue'].mean().round(2)
print(monthly_avg)

# Find the months with the highest and lowest revenue
print(f"n=== Peak month and slowest month ===")
print(f"Peak month: {monthly_avg.idxmax()} month, revenue {monthly_avg.max():,.0f}")
print(f"Slowest month: {monthly_avg.idxmin()} month, revenue {monthly_avg.min():,.0f}")

Output:

=== 创建多年月度数据 ===
   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 explanation:

  • A pivot table (pivot_table) makes it convenient to analyze the intersection of multiple years and months.
  • You can calculate the year-over-year growth rate for time series analysis.
  • idxmax()andidxmin()You can quickly find the month corresponding to the maximum or minimum value.

Notes

Important notes:

  • Series.dt.monthIt can only be used on Series of datetime64 type.
  • The returned month range is 1-12, where 1 represents January and 12 represents December.
  • If you need the month name, use thedt.month_name()method.
  • When handling data containing missing values (NaT),dt.monthit returns NaT at the corresponding positions.

Pandas 常用函数Pandas Common Functions

Other Extensions