Python Pandas - 建立一個 PeriodIndex 並設定頻率
要建立一個 PeriodIndex,請使用 pandas.PeriodIndex() 方法。要設定頻率,請使用 freq 引數。
首先,匯入所需的庫 −
import pandas as pd
建立一個 PeriodIndex 物件。PeriodIndex 是一個不可變的 ndarray,它儲存指示時間中規則日期的序數。我們使用“freq”引數設定了頻率 −
periodIndex = pd.PeriodIndex(['2021-09-25', '2020-10-30', '2020-11-20'], freq="D")
顯示 PeriodIndex 物件 −
print("PeriodIndex...\n", periodIndex)
示例
以下是程式碼 −
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(['2021-09-25', '2020-10-30', '2020-11-20'], freq="D") # Display PeriodIndex object print("PeriodIndex...\n", periodIndex) # Display day from the PeriodIndex object print("\nThe number of days from the PeriodIndex...\n", periodIndex.day)
輸出
這將產生以下程式碼 −
PeriodIndex... PeriodIndex(['2021-09-25', '2020-10-30', '2020-11-20'], dtype='period[D]') The number of days from the PeriodIndex... Int64Index([25, 30, 20], dtype='int64')
廣告