Python Pandas - 建立 PeriodIndex 並獲取該週期的天數


如需建立 PeriodIndex,請使用 pandas.PeriodIndex() 方法。使用 PeriodIndex.day 屬性來獲取該週期的天數。

首先,匯入所需庫 −

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 物件中顯示天數 −

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

示例

以下是程式碼 −

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)

輸出

這會生成以下程式碼 −

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')

更新時間:2021 年 10 月 20 日

910 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

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