pandas.DataFrame.to_timestamp#
- DataFrame.to_timestamp(freq=None, how='start', axis=0, copy=None)[源代码]#
将DataFrame转换为时间戳的DatetimeIndex,位于周期*开始*处。
- Parameters:
- freqstr,默认值为 PeriodIndex 的频率
所需频率。
- how{‘s’, ‘e’, ‘start’, ‘end’}
将周期转换为时间戳的约定;周期的开始或结束。
- 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 具有 DatetimeIndex。
Examples
>>> 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[ns]', freq=None)
使用 freq,这是 Timestamps 的偏移量
>>> 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[ns]', freq=None)