Để chuyển DateTimeIndex sang PeriodIndex (chu kỳ thời gian), sử dụng phương thức DateTimeIndex.to_period(freq).
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,
freq='2Y'
)
3. Chuyển sang Period với tần suất tháng ('M')
print("\nDateTimeIndex to Period (freq='M')...\n",
datetimeindex.to_period(freq='M'))
Ví dụ hoàn chỉnh
import pandas as pd
datetimeindex = pd.date_range(
'2021-10-18 07:20:32.261811624',
periods=5,
freq='2Y'
)
print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nDateTimeIndex to Period (freq='M')...\n",
datetimeindex.to_period(freq='M'))
Kết quả đầu ra
DateTimeIndex...
DatetimeIndex(['2021-12-31 07:20:32.261811624', '2023-12-31 07:20:32.261811624',
'2025-12-31 07:20:32.261811624', '2027-12-31 07:20:32.261811624',
'2029-12-31 07:20:32.261811624'],
dtype='datetime64[ns]', freq='2A-DEC')
DateTimeIndex to Period (freq='M')...
PeriodIndex(['2021-12', '2023-12', '2025-12', '2027-12', '2029-12'], dtype='period[M]')
Các tần suất (freq) thường dùng
| Mã | Ý nghĩa | Ví dụ |
|---|---|---|
| D | Ngày | 2021-12-31 |
| W | Tuần | 2021-12-27/2022-01-02 |
| M | Tháng | 2021-12 |
| Q | Quý | 2021Q4 |
| A / Y | Năm | 2021 |
| H | Giờ | 2021-12-31 07 |
| T / min | Phút | 2021-12-31 07:20 |
| S | Giây | 2021-12-31 07:20:32 |