pandas.DataFrame.to_period#

DataFrame.to_period(freq=None, axis=0, copy=<no_default>)[源代码][源代码]#

将 DataFrame 从 DatetimeIndex 转换为 PeriodIndex。

将 DataFrame 从 DatetimeIndex 转换为 PeriodIndex,并带有期望的频率(如果未传递,则从索引推断)。可以根据 axis 参数转换索引或列。

参数:
freqstr, 默认

PeriodIndex 的频率。

{0 或 ‘index’, 1 或 ‘columns’}, 默认 0

要转换的轴(默认是索引)。

复制布尔值, 默认为 False

如果为 False,则不会复制底层输入数据。

备注

copy 关键字将在 pandas 3.0 中更改行为。写时复制 将默认启用,这意味着所有带有 copy 关键字的方法将使用延迟复制机制来推迟复制并忽略 copy 关键字。copy 关键字将在 pandas 的未来版本中被移除。

通过启用写时复制 pd.options.mode.copy_on_write = True,您已经可以获得未来的行为和改进。

自 3.0.0 版本弃用.

返回:
DataFrame

带有转换后的 PeriodIndex 的 DataFrame。

参见

Series.to_period

Series 的等效方法

Series.dt.to_period

转换 DateTime 列的值。

示例

>>> idx = pd.to_datetime(
...     [
...         "2001-03-31 00:00:00",
...         "2002-05-31 00:00:00",
...         "2003-08-31 00:00:00",
...     ]
... )
>>> idx
DatetimeIndex(['2001-03-31', '2002-05-31', '2003-08-31'],
dtype='datetime64[s]', freq=None)
>>> idx.to_period("M")
PeriodIndex(['2001-03', '2002-05', '2003-08'], dtype='period[M]')

对于每年的频率

>>> idx.to_period("Y")
PeriodIndex(['2001', '2002', '2003'], dtype='period[Y-DEC]')