Python Pandas - 根據特定時間序列頻率從 DateTimeIndex 中提取年份


若要從具有特定時間序列頻率的 DateTimeIndex 中提取年份,請使用 DateTimeIndex.year 屬性。

首先,匯入所需庫 -

import pandas as pd

DatetimeIndex 的週期為 6,頻率為 Y,即年。時區為澳大利亞/悉尼 -

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

顯示 DateTimeIndex -

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

獲取年份 -

print("\nGetting the year name..\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("\nGetting the year name..\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>

Getting the year name..
   Int64Index([2021, 2022, 2023, 2024, 2025, 2026], dtype='int64')

更新於:19-Oct-2021

1K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.