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)

示例

以下为代码 −

Open Compiler
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 次浏览

开启你的事业

通过完成课程获取认证

开始
广告