我正在处理一些组织为带有 MultiIndex
的 df 的财务数据。包含股票代码和日期以及包含返回的列。我想知道是否应该将索引转换为 PeriodIndex
而不是 DateTimeIndex
因为返回实际上是在一段时间内而不是瞬间。除了哲学论证之外,还有哪些实用功能PeriodIndex
提供在这个特定用例中可能有用的东西 vs DateTimeIndex
?
最佳答案
DateTimeIndex 中有一些可用的函数(例如 is_month_start、is_quarter_end)在 PeriodIndex 中不可用。当 DateTimeIndex 无法获得我需要的格式时,我会使用 PeriodIndex。例如,如果我需要格式为 yyyy-mm 的每月频率,我使用 PeriodIndex。
例子:
假设 df 的索引为
df.index
'2020-02-26 13:50:00', '2020-02-27 14:20:00',
'2020-02-28 11:10:00', '2020-02-29 13:50:00'],
dtype='datetime64[ns]', name='peak_time', length=1025, freq=None)
最低月度数据可通过以下代码获取
dfg = df.groupby([df.index.year, df.index.month]).min()
其索引是 MultiIndex
dfg.index
MultiIndex([(2017, 1),
...
(2020, 1),
(2020, 2)],
names=['peak_time', 'peak_time'])
不,我将其转换为 PeriodIndex:
dfg["date"] = pd.PeriodIndex (dfg.index.map(lambda x: "{0}{1:02d}".format(*x)),freq="M")
关于python - 在 Pandas 中使用 PeriodIndex 与 DateTimeIndex ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50634824/