Để 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:
.261811624giây =261.811624mili-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 →
262mili-giây - Kết quả:
.262000giây (3 chữ số, phần dưới = 0)
So sánh round các tần suất
| freq | Gốc | Round | Quy tắc |
|---|---|---|---|
| 'us' | .261811624 | .261812 | nano ≥ 500 → lên |
| 'ms' | .261811624 | .262000 | micro ≥ 500 → lên |
| 'S' | 32.261811624 | 32 | phân giây < 0.5 → giữ |
| 'T' | 20:32.26 | 21:00 | giâ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.