Python Pandas – 将 DateTimeIndex 的时间戳对齐到最近的频率

Python Pandas – 将 DateTimeIndex 的时间戳对齐到最近的频率

要将 DateTimeIndex 的时间戳对齐到最近的频率,请使用 DateTimeIndex.snap() 方法。使用 freq 参数设置频率。

首先,导入所需的库 –

import pandas as pd

创建一个周期为6,频率为 D 即天的 DatetimeIndex –

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')

显示 DateTimeIndex –

print("DateTimeIndex...\n", datetimeindex)

将时间戳对齐到最近的频率,这里是月底 –

print("\nSnap time stamps to nearest occurring frequency...\n",
datetimeindex.snap(freq='M'))

示例

以下是代码 –

import pandas as pd

# 周期为6,频率为 D 即天的 DatetimeIndex
# 时区为 Australia/Adelaide
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')

# 显示 DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# 显示 DateTimeIndex 的频率
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)

# 将时间戳对齐到最近的频率,这里是月底
print("\nSnap time stamps to nearest occurring frequency...\n",
datetimeindex.snap(freq='M'))

输出结果

将生成以下代码 –

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+10:30', '2021-10-21 02:30:50+10:30',
'2021-10-22 02:30:50+10:30', '2021-10-23 02:30:50+10:30',
'2021-10-24 02:30:50+10:30', '2021-10-25 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='D')
DateTimeIndex frequency...
<Day>

Snap time stamps to nearest occurring frequency...
DatetimeIndex(['2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30',
'2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30',
'2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程