Python Pandas - 建立 PeriodIndex 並獲取星期幾


要建立一個 PeriodIndex,請使用 pandas.PeriodIndex() 方法。使用 PeriodIndex.dayofweek 屬性獲取星期幾。

首先,匯入必要的庫 −

import pandas as pd

建立一個 PeriodIndex 物件。PeriodIndex 是一個不可變的 ndarray,其中包含表示時間中規則週期的序數值。我們使用 "freq" 引數設定了頻率 −

periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

顯示 PeriodIndex 物件 −

print("PeriodIndex...\n", periodIndex)

從 PeriodIndex 物件顯示星期幾。星期幾顯示為星期一 = 0,星期二 = 1 ... 星期天 = 6 −

print("\nDays of the week from the PeriodIndex...\n", periodIndex.dayofweek)

示例

以下是程式碼 −

import pandas as pd

# Create a PeriodIndex object
# PeriodIndex is an immutable ndarray holding ordinal values indicating regular periods in time
# We have set the frequency using the "freq" parameter
periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

# Display PeriodIndex object
print("PeriodIndex...\n", periodIndex)

# Display PeriodIndex frequency
print("\nPeriodIndex frequency...\n", periodIndex.freq)

# Display day from the PeriodIndex object
print("\nThe number of days from the PeriodIndex...\n", periodIndex.day)

# Display day of the week from the PeriodIndex object
# Days of week are displayed as Monday=0, Tuesday=1 ... Sunday=6
print("\nDays of the week from the PeriodIndex...\n", periodIndex.dayofweek)

輸出

這將生成以下程式碼 −

PeriodIndex...
PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'],
dtype='period[D]')

PeriodIndex frequency...
<Day>

The number of days from the PeriodIndex...
Int64Index([25, 30, 20, 15, 12, 18], dtype='int64')

Days of the week from the PeriodIndex...
Int64Index([2, 2, 4, 2, 5, 6], dtype='int64')

更新於:20-Oct-2021

120 次瀏覽

開啟 職業生涯

透過完成課程獲取認證

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