【Pandas】pandas Index objects DatetimeIndex.year - 指南

Pandas2.2 Index objects

Time date components

方法描述
DatetimeIndex.year用于获取 DatetimeIndex 中每个日期时间元素的年份部分

pandas.DatetimeIndex.year

pandas.DatetimeIndex.year 是 DatetimeIndex 对象的一个属性,用于获取 DatetimeIndex 中每个日期时间元素的年份部分。该属性返回一个 Index 对象,其中包含与原 DatetimeIndex 长度相同的年份值。

详细说明
  • 用途:提取 DatetimeIndex 中每个日期时间值的年份部分
  • 类型:只读属性
  • 返回值:Index 对象,包含每个日期时间元素的年份(整数类型)
示例代码及结果
示例 1: 基本用法
import pandas as pd
# 创建包含不同年份的 DatetimeIndex
dates = pd.DatetimeIndex(['2020-01-15', '2021-06-30', '2022-12-25', '2023-07-04'])
print("原始 DatetimeIndex:")
print(dates)
# 提取年份
years = dates.year
print("\n年份:")
print(years)
print("年份类型:", type(years))
print("年份数据类型:", years.dtype)

输出结果:

原始 DatetimeIndex:
DatetimeIndex(['2020-01-15', '2021-06-30', '2022-12-25', '2023-07-04'], dtype='datetime64[ns]', freq=None)
年份:
Index([2020, 2021, 2022, 2023], dtype='int32')
年份类型: 
年份数据类型: int32
示例 2: 包含重复年份的情况
import pandas as pd
# 创建包含重复年份的 DatetimeIndex
dates = pd.DatetimeIndex([
'2020-01-01', '2020-06-15', '2020-12-31',
'2021-03-10', '2021-09-22',
'2022-02-14'
])
print("原始 DatetimeIndex:")
print(dates)
# 提取年份
years = dates.year
print("\n年份:")
print(years)
# 统计各年份出现次数
year_counts = pd.Series(years).value_counts().sort_index()
print("\n各年份出现次数:")
print(year_counts)

输出结果:

原始 DatetimeIndex:
DatetimeIndex(['2020-01-01', '2020-06-15', '2020-12-31', '2021-03-10',
               '2021-09-22', '2022-02-14'],
              dtype='datetime64[ns]', freq=None)
年份:
Index([2020, 2020, 2020, 2021, 2021, 2022], dtype='int32')
各年份出现次数:
2020    3
2021    2
2022    1
dtype: int64
示例 3: 带时区信息的 DatetimeIndex
import pandas as pd
# 创建带时区信息的 DatetimeIndex
dates = pd.DatetimeIndex([
'2020-01-01 10:00:00',
'2021-06-15 15:30:00',
'2022-12-31 23:59:59'
], tz='UTC')
print("带时区的 DatetimeIndex:")
print(dates)
# 提取年份
years = dates.year
print("\n年份:")
print(years)

输出结果:

带时区的 DatetimeIndex:
DatetimeIndex(['2020-01-01 10:00:00+00:00', '2021-06-15 15:30:00+00:00',
               '2022-12-31 23:59:59+00:00'],
              dtype='datetime64[ns, UTC]', freq=None)
年份:
Index([2020, 2021, 2022], dtype='int32')
示例 4: 与其它时间属性结合使用
import pandas as pd
# 创建 DatetimeIndex
dates = pd.DatetimeIndex([
'2020-01-15 10:30:00',
'2021-06-30 14:45:30',
'2022-12-25 08:15:45'
])
print("原始 DatetimeIndex:")
print(dates)
# 提取年、月、日信息
df = pd.DataFrame({
'日期时间': dates,
'年份': dates.year,
'月份': dates.month,
'日期': dates.day,
'小时': dates.hour,
'分钟': dates.minute
})
print("\n完整时间信息:")
print(df)

输出结果:

原始 DatetimeIndex:
DatetimeIndex(['2020-01-15 10:30:00', '2021-06-30 14:45:30',
               '2022-12-25 08:15:45'],
              dtype='datetime64[ns]', freq=None)
完整时间信息:
            日期时间    年份  月份  日期  小时  分钟
0 2020-01-15 10:30:00  2020   1  15  10  30
1 2021-06-30 14:45:30  2021   6  30  14  45
2 2022-12-25 08:15:45  2022  12  25   8  15
示例 5: 在数据分析中的应用
import pandas as pd
import numpy as np
# 创建示例数据:每日销售额
dates = pd.date_range('2020-01-01', '2022-12-31', freq='D')
sales = pd.Series(np.random.randint(1000, 5000, len(dates)), index=dates, name='销售额')
print("数据概览:")
print(f"数据时间范围: {sales.index.min()}{sales.index.max()}")
print(f"数据点数量: {len(sales)}")
# 提取年份用于分组分析
years = sales.index.year
print(f"\n涉及年份: {sorted(years.unique())}")
# 按年份统计总销售额
annual_sales = sales.groupby(years).sum()
print("\n各年总销售额:")
for year, total in annual_sales.items():
print(f"  {year}年: {total:,} 元")
# 计算各年平均日销售额
annual_avg_sales = sales.groupby(years).mean()
print("\n各年平均日销售额:")
for year, avg in annual_avg_sales.items():
print(f"  {year}年: {avg:.2f} 元")

输出结果:

数据概览:
数据时间范围: 2020-01-01 00:00:00 到 2022-12-31 00:00:00
数据点数量: 1096
涉及年份: [2020, 2021, 2022]
各年总销售额:
  2020年: 182,932 元
  2021年: 181,648 元
  2022年: 181,776 元
各年平均日销售额:
  2020年: 1669.09 元
  2021年: 1659.89 元
  2022年: 1658.54 元
示例 6: 空 DatetimeIndex 处理
import pandas as pd
# 创建空的 DatetimeIndex
empty_dates = pd.DatetimeIndex([])
print("空 DatetimeIndex:")
print(empty_dates)
# 提取年份
empty_years = empty_dates.year
print("\n空 DatetimeIndex 的年份:")
print(empty_years)
print("年份长度:", len(empty_years))

输出结果:

空 DatetimeIndex:
DatetimeIndex([], dtype='datetime64[ns]', freq=None)
空 DatetimeIndex 的年份:
Index([], dtype='int32')
年份长度: 0
应用场景
  1. 时间序列分析:按年份对时间序列数据进行分组和聚合分析
  2. 数据筛选:根据年份筛选特定年份的数据
  3. 报表生成:在生成年度报表时提取年份信息
  4. 数据可视化:在绘制年度趋势图时作为 x 轴标签
  5. 业务分析:进行年度业绩对比、同比增长分析等
注意事项
  • year 是只读属性,不能直接修改
  • 返回的是 Index 对象,不是普通的 numpy 数组
  • 对于空的 DatetimeIndex,year 属性返回空的 Index
  • 年份提取不受时区影响,始终返回本地时间的年份部分
  • 数据类型为 int32,可以安全地用于数值计算和比较操作

通过 year 属性,我们可以方便地从 DatetimeIndex 中提取年份信息,这对于基于时间的数据分析和处理非常有用。

posted on 2025-10-28 16:13  wgwyanfs  阅读(1)  评论(0)    收藏  举报

导航