Python Pandas - 檢查給定的 DateOffset 是否已錨定


要檢查給定的 DateOffset 是否已錨定,請在 Pandas 中使用 offset.is_anchored() 方法。首先,匯入所需的庫 −

from pandas.tseries.frequencies import to_offset
import pandas as pd

在 Pandas 中設定時間戳物件 −

timestamp = pd.Timestamp('2021-09-26 03:25:02.000045')

建立 DateOffset。在這裡,我們使用錨定偏移,即星期頻率,具體為星期二 −

offset = to_offset("W-TUE")

顯示更新的時間戳 −

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

檢查 DateOffset 是否已錨定 −

print("\nCheck whether the DateOffset is anchored...\n", offset.is_anchored())

示例

以下是程式碼 −

from pandas.tseries.frequencies import to_offset
import pandas as pd

# Set the timestamp object in Pandas
timestamp = pd.Timestamp('2021-09-26 03:25:02.000045')

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

# Create the DateOffset
# We are using the Anchored offset i.e. weekly frequency here for Tuesday
offset = to_offset("W-TUE")

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

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

# Check whether the DateOffset is anchored
print("\nCheck whether the DateOffset is anchored...\n", offset.is_anchored())

輸出

這將生成以下程式碼 −

Timestamp...
 2021-09-26 03:25:02.000045

DateOffset...
 <Week: weekday=1>

Updated Timestamp...
 2021-09-28 03:25:02.000045

Check whether the DateOffset is anchored...
 True

更新於:21-Oct-2021

81 檢視

開啟您的 職業生涯

完成課程以獲取認證

開始
廣告
© . All rights reserved.