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

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

Để làm tròn lên (ceil) DateTimeIndex đến tần suất phút, dùng DateTimeIndex.ceil(freq='T') (hoặc 'min').

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. Ceil phút

print("\nCeil phút...\n",
      datetimeindex.ceil(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("\nCeil phút...\n",
      datetimeindex.ceil(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')

Ceil phút...
DatetimeIndex(['2021-10-18 07:21:00+10:30', '2021-10-18 07:22:00+10:30',
               '2021-10-18 07:22:00+10:30', '2021-10-18 07:23:00+10:30',
               '2021-10-18 07:24: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/phân giây lẻ)
  • Ceil phút: làm tròn lên đến phút nguyên tiếp theo → 21, 22, 22, 23, 24
  • Giây/phân giây được reset về 0
  • Lưu ý: 2 giá trị cùng phút 21 → cùng ceil thành 22

Ký hiệu tần suất phút

  • 'T' hoặc 'min': Phút (từ "minute")
  • 'H' hoặc 'h': Giờ
  • 'D' hoặc 'd': Ngày
  • 'W': Tuần
  • 'M': Tháng (cuối tháng)
  • 'Q': Quý
  • 'A' / 'Y': Năm

Lưu ý: Pandas dùng 'T' cho phút để tránh nhầm lẫn với 'M' (tháng) và 'm' (phút trong một số ngữ cảnh cũ).