Python Pandas - 將週期轉換為所需頻率


如要將週期轉換為所需頻率,請使用 Period.asfreq() 方法。我們假設使用“H”說明符將所需頻率設定為每小時頻率。

首先,匯入所需的庫 −

import pandas as pd

pandas.Period 表示一個時間週期。建立兩個週期物件

period1 = pd.Period("2020-09-23 03:15:40")
period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, minute = 35)

顯示週期物件

print("Period1...\n", period1)
print("Period2...\n", period2)

將週期轉換為所需頻率。已將頻率設定為 H,即每小時頻率

res1 = period1.asfreq('H')
res2 = period2.asfreq('H')

示例

以下是程式碼

import pandas as pd

# The pandas.Period represents a period of time
# creating two Period objects
period1 = pd.Period("2020-09-23 03:15:40")
period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, minute = 35)

# display the Period objects
print("Period1...\n", period1)
print("Period2...\n", period2)

# Convert Period to desired frequency
# We have set frequency as H i.e. Hourly frequency
res1 = period1.asfreq('H')
res2 = period2.asfreq('H')

# Return the year from the two Period objects
print("\nResult after conversion from the 1st Period object ...\n", res1)
print("\nResult after conversion from the 2nd Period object...\n", res2)

輸出

這將生成以下程式碼

Period1...
2020-09-23 03:15:40
Period2...
2021-04-16

Result after conversion from the 1st Period object ...
2020-09-23 03:00

Result after conversion from the 2nd Period object...
2021-04-16 23:00

更新於: 20-Oct-2021

532 次瀏覽

開啟你的 職業 生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.