Python Pandas - 如何使用毫秒頻率對 DateTimeIndex 進行舍入


若要使用毫秒頻率對 DateTimeIndex 進行四捨五入,請使用 DateTimeIndex.round() 方法。對於毫秒頻率,請將 freq 引數與值 “ms” 結合使用。

首先,匯入所需的庫 −

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 日期進行舍入操作。對於毫秒頻率,我們使用了“ms” −

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

示例

程式碼如下 −

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)

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

輸出

生成以下程式碼 −

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>

Performing round operation with milliseconds frequency...
DatetimeIndex(['2021-09-29 07:20:32.262000+09:30',
'2021-09-29 07:21:00.262000+09:30',
'2021-09-29 07:21:28.262000+09:30',
'2021-09-29 07:21:56.262000+09:30',
'2021-09-29 07:22:24.262000+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

更新日期: 2021 年 10 月 19 日

1000 多次瀏覽

開啟你的職業生涯

透過完成課程認證

開始
廣告
© . All rights reserved.