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

Python Pandas: Trả về số lần tăng trên DateOffset object

Thuộc tính offset.n trong Pandas trả về số lần tăng (count of increments) được áp dụng trên đối tượng DateOffset.

Các bước thực hiện

1. Import thư viện

from pandas.tseries.frequencies import to_offset
import pandas as pd

2. Thiết lập timestamp

timestamp = pd.Timestamp('2021-09-26 03:25:02.000045')

3. Tạo DateOffset với tần suất tháng (5 tháng)

offset = to_offset("5M")

4. Hiển thị timestamp cập nhật

print("\nUpdated Timestamp...\n", timestamp + offset)

5. Lấy số lần tăng

print("\nSố lần tăng trên DateOffset object..\n", offset.n)

Ví dụ hoàn chỉnh

from pandas.tseries.frequencies import to_offset
import pandas as pd

timestamp = pd.Timestamp('2021-09-26 03:25:02.000045')
print("Timestamp...\n", timestamp)

offset = to_offset("5M")
print("\nDateOffset...\n", offset)
print("\nUpdated Timestamp...\n", timestamp + offset)
print("\nSố lần tăng trên DateOffset object..\n", offset.n)

Kết quả đầu ra

Timestamp...
2021-09-26 03:25:02.000045
DateOffset...
<5 * MonthEnds>
Updated Timestamp...
2022-01-31 03:25:02.000045
Số lần tăng trên DateOffset object..
5

Giải thích:

  • 5M = 5 lần MonthEnd (cuối tháng)
  • Từ 26/9/2021 cộng 5 tháng cuối → 31/1/2022 (cuối tháng 1)
  • offset.n trả về 5 - chính xác số lượng increment

Lưu ý: MonthEnd luôn nhảy đến cuối tháng, không giữ nguyên ngày. Nếu muốn giữ ngày, sử dụng DateOffset(months=5).