Để tạo PeriodIndex trong Pandas, sử dụng constructor pandas.PeriodIndex() với tham số freq chỉ định tần suất (frequency) của các period.
Các bước thực hiện
1. Import thư viện
import pandas as pd
2. Tạo PeriodIndex với tần suất ngày
periodIndex = pd.PeriodIndex(
['2021-09-25', '2020-10-30', '2020-11-20'],
freq="D"
)
3. Hiển thị PeriodIndex
print("PeriodIndex...\n", periodIndex)
Ví dụ hoàn chỉnh
import pandas as pd
periodIndex = pd.PeriodIndex(
['2021-09-25', '2020-10-30', '2020-11-20'],
freq="D"
)
print("PeriodIndex...\n", periodIndex)
print("\nNgày trong tháng từ PeriodIndex...\n", periodIndex.day)
Kết quả đầu ra
PeriodIndex...
PeriodIndex(['2021-09-25', '2020-10-30', '2020-11-20'], dtype='period[D]')
Ngày trong tháng từ PeriodIndex...
Int64Index([25, 30, 20], dtype='int64')
Các tần suất (freq) phổ biến cho PeriodIndex
| Freq string | Tần suất | Ví dụ period |
|---|---|---|
'A' / 'Y' |
Năm (YearEnd) | 2021, 2022 |
'Q' |
Quý (QuarterEnd) | 2021Q1, 2021Q2 |
'M' |
Tháng (MonthEnd) | 2021-01, 2021-02 |
'W' |
Tuần (Week) | 2021-01, 2021-02 (tuần 1, 2) |
'D' |
Ngày (Day) | 2021-09-25 |
'B' |
Ngày làm việc (BusinessDay) | 2021-09-24 (Thứ 6) |
'H' |
Giờ (Hour) | 2021-09-25 07:00 |
'T' / 'min' |
Phút (Minute) | 2021-09-25 07:30 |
'S' |
Giây (Second) | 2021-09-25 07:30:35 |
Tạo PeriodIndex từ dãy số (range)
# Tạo 10 ngày liên tiếp từ 2021-01-01
idx = pd.period_range(start='2021-01-01', periods=10, freq='D')
print(idx)
# PeriodIndex(['2021-01-01', '2021-01-02', ..., '2021-01-10'], dtype='period[D]')
Lưu ý: period_range() thường tiện hơn khi tạo dãy period liên tục.