Python Pandas - 建立 PeriodIndex 並獲取該年的第幾天


要建立一個 PeriodIndex,請使用 pandas.PeriodIndex() 方法。使用 PeriodIndex.dayofyear 屬性獲取該年的第幾天。

首先,匯入必需的庫 −

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("\nDays of the year from the PeriodIndex...\n", periodIndex.dayofyear)

示例

以下為程式碼 −

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 year from the PeriodIndex object
print("\nDays of the year from the PeriodIndex...\n", periodIndex.dayofyear)

輸出

這將生成以下程式碼 −

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 year from the PeriodIndex...
Int64Index([206, 303, 325, 258, 71, 169], dtype='int64')

更新於: 2021 年 10 月 20 日

130 次瀏覽

開啟你的事業

透過完成課程獲取認證

開始
廣告
© . All rights reserved.