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

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

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

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

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

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("\nRound mili-giây...\n",
      datetimeindex.round(freq='ms'))

Kết quả đầu ra

DateTimeIndex...
DatetimeIndex(['2021-09-29 07:20:32.261811624+09:30', ...],
              dtype='datetime64[ns, Australia/Adelaide]', freq='28S')

Round mili-giây...
DatetimeIndex(['2021-09-29 07:20:32.262000+09:30', ...],
              dtype='datetime64[ns, Australia/Adelaide]', freq=None)

Giải thích

  • Gốc: .261811624 giây = 261.811624 mili-giây
  • Round mili-giây: làm tròn đến mili-giây gần nhất. Phần micro = 811.624 ≥ 500 → làm tròn lên → 262 mili-giây
  • Kết quả: .262000 giây (3 chữ số, phần dưới = 0)

So sánh round các tần suất

freqGốcRoundQuy tắc
'us'.261811624.261812nano ≥ 500 → lên
'ms'.261811624.262000micro ≥ 500 → lên
'S'32.26181162432phân giây < 0.5 → giữ
'T'20:32.2621:00giây ≥ 30 → lên phút

Lưu ý: Round Half to Even áp dụng cho mọi tần suất. Khi chính xác giữa 2 giá trị, chọn giá trị chẵn.