Python Pandas——如何利用秒频率对 DateTimeIndex 进行舍入


要对 DateTimeIndex 进行秒频率舍入,请使用 DateTimeIndex.round() 方法。对于秒频率,请将 freq 参数值设置为 ‘S’

首先,导入必需的库 −

import pandas as pd

使用周期为 5 且频率为 s(即秒)创建 DatetimeIndex −

datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='28s')

对日期为秒频率的 DateTimeIndex 执行舍入运算。对于秒频率,我们使用了 'S' −

print("\nPerforming round operation with seconds frequency...\n",
datetimeindex.round(freq='S'))

示例

以下是代码 −

import pandas as pd

# DatetimeIndex with period 5 and frequency as s i.e. seconds
# timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='28s')

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

# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# getting the second
res = datetimeindex.second

# display only the second
print("\nThe second from DateTimeIndex...\n", res)

# Round operation on DateTimeIndex date with seconds frequency
# For seconds frequency, we have used 'S'
print("\nPerforming round operation with seconds frequency...\n",
datetimeindex.round(freq='S'))

输出

这将生成以下代码 −

DateTimeIndex...
DatetimeIndex(['2021-09-29 07:20:32.261811624+09:30',
'2021-09-29 07:21:00.261811624+09:30',
'2021-09-29 07:21:28.261811624+09:30',
'2021-09-29 07:21:56.261811624+09:30',
'2021-09-29 07:22:24.261811624+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='28S')
DateTimeIndex frequency...
<28 * Seconds>

The second from DateTimeIndex...
Int64Index([32, 0, 28, 56, 24], dtype='int64')

Performing round operation with seconds frequency...
DatetimeIndex(['2021-09-29 07:20:32+09:30', '2021-09-29 07:21:00+09:30',
'2021-09-29 07:21:28+09:30', '2021-09-29 07:21:56+09:30',
'2021-09-29 07:22:24+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

更新于: 19-10-2021

815 次浏览

开启您的事业

通过完成课程获得认证

开始学习
广告