Thuộc tính offset.freqstr trong Pandas trả về tần suất (frequency) được áp dụng trên đối tượng DateOffset dưới dạng chuỗi (string).
Các bước thực hiện
1. Import thư viện
from pandas.tseries.offsets import DateOffset
import pandas as pd
2. Thiết lập timestamp
timestamp = pd.Timestamp('2021-08-30 02:30:55')
3. Tạo DateOffset (3 tháng)
offset = pd.tseries.offsets.DateOffset(months=3)
4. Hiển thị timestamp cập nhật
print("\nUpdated Timestamp...\n", timestamp + offset)
5. Lấy tần suất dạng chuỗi
print("\nTần suất trên DateOffset...\n", offset.freqstr)
Ví dụ hoàn chỉnh
from pandas.tseries.offsets import DateOffset
import pandas as pd
timestamp = pd.Timestamp('2021-08-30 02:30:55')
print("Timestamp...\n", timestamp)
offset = pd.tseries.offsets.DateOffset(months=3)
print("\nDateOffset...\n", offset)
print("\nUpdated Timestamp...\n", timestamp + offset)
print("\nTần suất trên DateOffset...\n", offset.freqstr)
Kết quả đầu ra
Timestamp...
2021-08-30 02:30:55
DateOffset...
<DateOffset: months=3>
Updated Timestamp...
2021-11-30 02:30:55
Tần suất trên DateOffset...
<DateOffset: months=3>
Lưu ý quan trọng: Khi tạo DateOffset qua constructor DateOffset(months=3) thay vì to_offset("3M"), freqstr trả về chuỗi biểu diễn object "<DateOffset: months=3>" thay vì mã tần suất chuẩn "3M". Điều này khác với các offset tạo từ to_offset().
So sánh hai cách tạo
| Cách tạo | freqstr | rule_code | name |
|---|---|---|---|
to_offset("3M") |
3M |
M |
M |
DateOffset(months=3) |
<DateOffset: months=3> |
None |
DateOffset |
Khuyến nghị: Sử dụng to_offset() cho các tần suất chuẩn để có freqstr đúng chuẩn.