Python Pandas - 如何将 DateTimeIndex 转换为 Period
pythonserver side programmingprogramming更新于 2026/1/21 22:36:17
要将 DateTimeIndex 转换为 Period,请使用 Pandas 中的 datetimeindex.to_period() 方法。使用 freq 参数设置频率。
首先,导入所需的库 −
import pandas as pd
创建一个 DatetimeIndex,周期为 5,频率为 Y,即年份 −
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')
显示 DateTimeIndex −
print("DateTimeIndex...\n", datetimeindex)
将 DateTimeIndex 转换为 Period。我们使用值为 'M' 的 "freq" 参数将频率设置为 Month −
print("\nConvert DateTimeIndex to Period...\n",
datetimeindex.to_period(freq='M'))
示例
以下是代码 −
import pandas as pd
# DatetimeIndex 周期为 5,频率为 Y,即年份
# 时区为澳大利亚/阿德莱德
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')
# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
# 显示 DateTimeIndex 频率
print("DateTimeIndex 频率...\n", datetimeindex.freq)
# 将 DateTimeIndex 转换为 Period
# 我们使用值为 'M' 的 "freq" 参数将频率设置为 Month
print("\nConvert DateTimeIndex to Period...\n",
datetimeindex.to_period(freq='M'))
输出
这将产生以下代码 −
DateTimeIndex... DatetimeIndex(['2021-12-31 07:20:32.261811624', '2023-12-31 07:20:32.261811624', '2025-12-31 07:20:32.261811624', '2027-12-31 07:20:32.261811624', '2029-12-31 07:20:32.261811624'], dtype='datetime64[ns]', freq='2A-DEC') DateTimeIndex 频率... <2 * YearEnds: month=12> Convert DateTimeIndex to Period... PeriodIndex(['2021-12', '2023-12', '2025-12', '2027-12', '2029-12'], dtype='period[M]')
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/
打印
下一节:Python Pandas - 计算索引值与在指定频率下转换为 PeriodArray 的索引之间的差异的 TimedeltaArray ❯❮ 上一节:用 Python 编写程序来查找一个列表中第 k 个最大索引值

