pandas.DataFrame.to_period#
- DataFrame.to_period(freq=None, axis=0, copy=None)[源代码]#
将 DataFrame 从 DatetimeIndex 转换为 PeriodIndex。
将 DataFrame 从 DatetimeIndex 转换为具有所需频率(如果未传递,则从索引推断)的 PeriodIndex。
- Parameters:
- freqstr, default
PeriodIndex 的频率。
- axis{0 或 ‘index’, 1 或 ‘columns’}, default 0
要转换的轴(默认为索引)。
- copybool, default True
如果为 False,则不对底层输入数据进行复制。
备注
copy 关键字在 pandas 3.0 中将更改行为。Copy-on-Write 将默认启用,这意味着所有带有 copy 关键字的方法都将使用惰性复制机制来延迟复制并忽略 copy 关键字。copy 关键字将在 pandas 的未来版本中移除。
通过启用 copy on write
pd.options.mode.copy_on_write = True,您可以获得未来的行为和改进。
- Returns:
- DataFrame
DataFrame 具有 PeriodIndex。
Examples
>>> 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[ns]', 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]')