Python Pandas – 从带有特定时间序列频率的DateTimeIndex中提取年份

Python Pandas – 从带有特定时间序列频率的DateTimeIndex中提取年份

要从具有特定时间序列频率的DateTimeIndex中提取年份,请使用 DateTimeIndex.year 属性。

首先,导入所需的库−

import pandas as pd

具有6个周期和频率为Y(即年份)的DatetimeIndex。时区为Australia/Sydney−

datetimeindex = pd.date_range('2021-09-24 02:35:55', periods=6, tz='Australia/Sydney',freq='Y')

显示DateTimeIndex−

print("DateTimeIndex...\n", datetimeindex)

获取年份−

print("\n获取年份..\n",datetimeindex.year)

示例

以下是代码−

import pandas as pd

# DatetimeIndex with period 6 and frequency as Y i.e. years
# timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-09-24 02:35:55', periods=6, tz='Australia/Sydney', freq='Y')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# get the year
print("\n获取年份..\n",datetimeindex.year)

输出

这将生成以下输出−

DateTimeIndex...
DatetimeIndex(['2021-12-31 02:35:55+11:00', '2022-12-31 02:35:55+11:00',
               '2023-12-31 02:35:55+11:00', '2024-12-31 02:35:55+11:00',
               '2025-12-31 02:35:55+11:00', '2026-12-31 02:35:55+11:00'],
               dtype='datetime64[ns, Australia/Sydney]', freq='A-DEC')
DateTimeIndex frequency...
   <YearEnd: month=12>

获取年份..
   Int64Index([2021, 2022, 2023, 2024, 2025, 2026], dtype='int64')

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程