pandas.DataFrame.to_timestamp#
- DataFrame.to_timestamp(freq=None, how='start', axis=0, copy=<no_default>)[源代码]#
将 PeriodIndex 转换为时间戳的 DatetimeIndex,在周期的开始处。
通过指定 how=”e”,可以将其更改为周期的结束。
- 参数:
- freqstr, PeriodIndex 的默认频率
所需的频率。
- how{‘s’, ‘e’, ‘start’, ‘end’}
将周期转换为时间戳的约定;周期的开始 vs. 结束。
- axis{0 或 ‘index’, 1 或 ‘columns’}, 默认为 0
要转换的轴(默认为索引)。
- copybool,默认值 False
此关键字已被忽略;更改其值将不会影响方法。
已弃用,版本 3.0.0: 此关键字已被忽略,并将在 pandas 4.0 中删除。自 pandas 3.0 起,此方法始终返回一个新对象,并使用延迟复制机制,该机制会推迟复制直到必要时(写时复制)。有关更多详细信息,请参阅关于写时复制的用户指南。
- 返回:
- 具有 DatetimeIndex 的 DataFrame
具有已转换为 DatetimeIndex 的 PeriodIndex 的 DataFrame。
另请参阅
DataFrame.to_period将 DatetimeIndex 转换为 PeriodIndex 的逆向方法。
Series.to_timestampSeries 的等效方法。
示例
>>> idx = pd.PeriodIndex(["2023", "2024"], freq="Y") >>> d = {"col1": [1, 2], "col2": [3, 4]} >>> df1 = pd.DataFrame(data=d, index=idx) >>> df1 col1 col2 2023 1 3 2024 2 4
在这种情况下,生成的时间戳将位于年份的开头
>>> df1 = df1.to_timestamp() >>> df1 col1 col2 2023-01-01 1 3 2024-01-01 2 4 >>> df1.index DatetimeIndex(['2023-01-01', '2024-01-01'], dtype='datetime64[us]', freq=None)
使用 freq,即时间戳的偏移量
>>> df2 = pd.DataFrame(data=d, index=idx) >>> df2 = df2.to_timestamp(freq="M") >>> df2 col1 col2 2023-01-31 1 3 2024-01-31 2 4 >>> df2.index DatetimeIndex(['2023-01-31', '2024-01-31'], dtype='datetime64[us]', freq=None)