Python Pandas - 返回給定 DateOffset 物件的頻率作為字串


要返回給定 DateOffset 物件上應用的頻率作為字串,請在 Pandas 中使用 **offset.freqstr** 屬性。

首先,匯入所需的庫 -

from pandas.tseries.offsets import DateOffset
import pandas as pd

在 Pandas 中設定時間戳物件 -

timestamp = pd.Timestamp('2021-08-30 02:30:55')

建立 DateOffset。我們在這裡使用“months”引數遞增月份 -

offset = pd.tseries.offsets.DateOffset(months=3)

顯示更新的時間戳 -

print("\nUpdated Timestamp...\n",timestamp + offset)

作為字串返回給定 DateOffset 物件上應用的頻率 -

print("\nFrequency on the given DataOffset...\n",offset.freqstr)

示例

以下是程式碼 -

from pandas.tseries.offsets import DateOffset
import pandas as pd

# Set the timestamp object in Pandas
timestamp = pd.Timestamp('2021-08-30 02:30:55')

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

# Create the DateOffset
# We are incrementing the months here using the "months" parameter
offset = pd.tseries.offsets.DateOffset(months=3)

# Display the DateOffset
print("\nDateOffset...\n",offset)

# Display the Updated Timestamp
print("\nUpdated Timestamp...\n",timestamp + offset)

# frequency applied on the given DateOffset object as a string
print("\nFrequency on the given DataOffset...\n",offset.freqstr)

輸出

這將生成以下程式碼 -

Timestamp...
2021-08-30 02:30:55

DateOffset...
<DateOffset: months=3>

Updated Timestamp...
2021-11-30 02:30:55

Frequency on the given DataOffset...
<DateOffset: months=3>

更新於: 2021-10-21

104 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.