Python Pandas - 创建一个 PeriodIndex 并获取一个月中的哪一天
要创建PeriodIndex,请使用方法。使用PeriodIndex.daysinmonth属性获取月份中的天数pandas.PeriodIndex()
首先,导入所需的库-
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 #CreateaPeriodIndexobject #PeriodIndexisanimmutablendarrayholdingordinalvaluesindicatingregularperiodsintime # 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") #DisplayPeriodIndexobject print("PeriodIndex...\n", periodIndex) #DisplayPeriodIndexfrequency print("\nPeriodIndex frequency...\n", periodIndex.freq) #Displaythemonthnumberi.e.1=January,2=February...12=December print("\nMonth number...\n", periodIndex.month) #DisplaydaysinthespecificmonthfromthePeriodIndexobject 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')