Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Round DateTimeIndex với tần suất giây

Để làm tròn (round) DateTimeIndex đến tần suất giây, dùng DateTimeIndex.round(freq='S').

Các bước thực hiện

1. Import thư viện

import pandas as pd

2. Tạo DateTimeIndex

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

3. Lấy thành phần giây (tham khảo)

print("Giây từ DateTimeIndex...\n", datetimeindex.second)

4. Round giây

print("\nRound giây...\n",
      datetimeindex.round(freq='S'))

Ví dụ hoàn chỉnh

import pandas as pd

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

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nGiây từ DateTimeIndex...\n", datetimeindex.second)
print("\nRound giây...\n",
      datetimeindex.round(freq='S'))

Kết quả đầu ra

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')

Giây từ DateTimeIndex...
Int64Index([32, 0, 28, 56, 24], dtype='int64')

Round giây...
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)

Giải thích

  • Gốc: giây 32.26, 0.26, 28.26, 56.26, 24.26
  • Round giây: phần phân giây < 0.5 → giữ nguyên giây nguyên
    • 32.26 → 32
    • 0.26 → 0
    • 28.26 → 28
    • 56.26 → 56
    • 24.26 → 24
  • Kết quả không có phần lẻ giây

So sánh floor/ceil/round giây

Gốcfloor('S')ceil('S')round('S')
32.26323332
0.26010
28.26282928
56.26565756
24.26242524

Vì tất cả phần phân giây < 0.5, round = floor trong trường hợp này.