Python Pandas - 建立 PeriodIndex 並獲取月份中的天數
要建立 PeriodIndex,使用 pandas.PeriodIndex() 方法。使用 PeriodIndex.daysinmonth 屬性獲取月份的天數
首先,匯入所需的庫 −
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 specific month from the PeriodIndex...\n", periodIndex.daysinmonth)範例
以下是程式碼 −
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 the month number i.e. 1 = January, 2 = February ... 12 = December
print("\nMonth number...\n", periodIndex.month)
# Display days in the specific month from the PeriodIndex object
print("\nDays of the specific month from the PeriodIndex...\n", periodIndex.daysinmonth)輸出
這會產生以下程式碼 −
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> Month number... Int64Index([7, 10, 11, 9, 3, 6], dtype='int64') Days of the specific month from the PeriodIndex... Int64Index([31, 31, 30, 30, 31, 30], dtype='int64')
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP