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

Python Pandas - Floor DateTimeIndex với tần suất phút

Để làm tròn xuống (floor) DateTimeIndex đến tần suất phút, dùng DateTimeIndex.floor(freq='T').

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 phút (tham khảo)

print("Phút từ DateTimeIndex...\n", datetimeindex.minute)

4. Floor phút

print("\nFloor phút...\n",
      datetimeindex.floor(freq='T'))

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("\nPhút từ DateTimeIndex...\n", datetimeindex.minute)
print("\nFloor phút...\n",
      datetimeindex.floor(freq='T'))

Kết quả đầu ra

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

Phút từ DateTimeIndex...
Int64Index([20, 21, 21, 22, 23], dtype='int64')

Floor phút...
DatetimeIndex(['2021-10-18 07:20:00+10:30', '2021-10-18 07:21:00+10:30',
               '2021-10-18 07:21:00+10:30', '2021-10-18 07:22:00+10:30',
               '2021-10-18 07:23:00+10:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq=None)

Giải thích

  • Gốc: phút 20, 21, 21, 22, 23 (có giây lẻ)
  • Floor phút: cắt bỏ giây/phân giây, giữ nguyên phút → 20, 21, 21, 22, 23
  • 2 giá trị cùng phút 21 → cùng floor thành 21:00
  • Khác với ceil('T'): floor giữ nguyên phút, ceil tăng lên phút tiếp theo

So sánh floor/ceil/round phút

Gốcfloor('T')ceil('T')round('T')
20:3220:0021:0021:00 (≥30s)
21:1221:0022:0021:00 (<30s)
21:5221:0022:0022:00 (≥30s)

Ứng dụng: Groupby theo phút, resample dữ liệu time-series, align timestamp đến ranh giới phút.