Python Pandas - 轉換為 Period 的 DateTimeIndex


若要轉換為 Period 的 DateTimeIndex,請使用 Pandas 中的 datetimeindex.to_period() 方法。使用 freq 引數設定頻率。

首先匯入所需的庫 −

import pandas as pd

建立一個 DateTimeIndex,週期為 5,頻率為 Y,即年 −

datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')

顯示 DateTimeIndex −

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

轉換為 Period 的 DateTimeIndex。使用值“M”將“freq”引數設定的頻率為月份 −

print("\nConvert DateTimeIndex to Period...\n",
datetimeindex.to_period(freq='M'))

示例

以下是程式碼 −

import pandas as pd

# DatetimeIndex with period 5 and frequency as Y i.e. year
# timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')

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

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

# Convert DateTimeIndex to Period
# We have set the frequency as Month using the "freq" parameter with value 'M'
print("\nConvert DateTimeIndex to Period...\n",
datetimeindex.to_period(freq='M'))

輸出

將生成以下程式碼 −

DateTimeIndex...
DatetimeIndex(['2021-12-31 07:20:32.261811624',
'2023-12-31 07:20:32.261811624',
'2025-12-31 07:20:32.261811624',
'2027-12-31 07:20:32.261811624',
'2029-12-31 07:20:32.261811624'],
dtype='datetime64[ns]', freq='2A-DEC')
DateTimeIndex frequency...
<2 * YearEnds: month=12>

Convert DateTimeIndex to Period...
PeriodIndex(['2021-12', '2023-12', '2025-12', '2027-12', '2029-12'], dtype='period[M]')

更新於: 2021-10-19

2 千+ 瀏覽量

事業起航

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.