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

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

Để làm tròn xuống (floor) DateTimeIndex đến tần suất giây, dùng DateTimeIndex.floor(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-10-18 07:20:32.261811624',
    periods=5,
    tz='Australia/Adelaide',
    freq='40S'
)

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

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

4. Floor giây

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

Ví dụ hoàn chỉnh

import pandas as pd

datetimeindex = pd.date_range(
    '2021-10-18 07:20:32.261811624',
    periods=5,
    tz='Australia/Adelaide',
    freq='40S'
)

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

Kết quả đầu ra

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

Giây từ DateTimeIndex...
Int64Index([32, 12, 52, 32, 12], dtype='int64')

Floor giây...
DatetimeIndex(['2021-10-18 07:20:32+10:30', '2021-10-18 07:21:12+10:30',
               '2021-10-18 07:21:52+10:30', '2021-10-18 07:22:32+10:30',
               '2021-10-18 07:23:12+10:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq=None)

Giải thích

  • Gốc: có phần lẻ giây (nano/micro/mili)
  • Floor giây: cắt bỏ phần lẻ, giữ nguyên giây nguyên → 32, 12, 52, 32, 12
  • Khác với ceil('S'): floor giữ nguyên giây, ceil tăng lên giây tiếp theo nếu có phần lẻ

Tóm tắt floor các tần suất

freqGốcFloor
'us'.261811624.261811
'ms'.261811624.261000
'S'32.26181162432
'T'20:32.2620:00
'H'07:20:3207:00:00

Lưu ý: floor không bao giờ tăng giá trị thời gian, chỉ giữ nguyên hoặc giảm.