Python Pandas - 從帶有特定時間序列頻率的 DateTimeIndex 中提取月份


如要從帶有特定時間序列頻率的 DateTimeIndex 中提取月份,請使用 DateTimeIndex.month 屬性。

首先,匯入所需的庫 −

import pandas as pd

DatetimeIndex 的週期為 6,頻率為 M,即月份。時區為澳大利亞/悉尼 −

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

顯示 DateTimeIndex −

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

獲取月份,即 1 月=1,2 月=2,...,12 月=12 −

print("\nGetting the month number..\n",datetimeindex.month)

示例

以下是程式碼 −

import pandas as pd

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

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

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

# get the month number i.e. January=1, february=2, ..., December=12
print("\nGetting the month number..\n",datetimeindex.month)

輸出

會生成以下輸出 −

DateTimeIndex...
DatetimeIndex(['2021-09-30 02:35:55+10:00', '2021-10-31 02:35:55+11:00',
               '2021-11-30 02:35:55+11:00', '2021-12-31 02:35:55+11:00',
               '2022-01-31 02:35:55+11:00', '2022-02-28 02:35:55+11:00'],
               dtype='datetime64[ns, Australia/Sydney]', freq='M')
DateTimeIndex frequency...
   <MonthEnd>

Getting the month number..
   Int64Index([9, 10, 11, 12, 1, 2], dtype='int64')

更新於: 19-Oct-2021

已檢視 1K+ 次

開啟你的 職業 生涯

課程完成後獲得認證

開始
廣告
© . All rights reserved.