Python Pandas - 使用季度頻率將給定的時間戳轉換為頻率


要將給定的時間戳轉換為頻率,請使用 **timestamp.to_period()** 方法。其中,使用 **freq** 引數設定頻率。對於季度頻率,將 freq 設定為 Q。

首先,匯入所需的庫:

import pandas as pd

在 Pandas 中建立時間戳物件

timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)

將時間戳轉換為頻率。使用值 'Q' 的 "freq" 引數將頻率設定為季度

timestamp.to_period(freq='Q')

示例

以下是程式碼

import pandas as pd

# set the timestamp object in Pandas
timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)

# display the Timestamp
print("Timestamp...\n", timestamp)

# convert timestamp to Period
# we have set the frequency as quarterly using the "freq" parameter with value 'Q'
print("\nTimestamp to Period with quarterly frequency...\n", timestamp.to_period(freq='Q'))

輸出

這將生成以下程式碼

Timestamp...
 2021-09-18 11:50:20.000033
Timestamp to Period with quarterly frequency...
 2021Q3

更新於: 2021-10-13

550 瀏覽

開啟你的 職業生涯

完成課程以獲取認證

開始
廣告
© . All rights reserved.