Thuộc tính PeriodIndex.month trong Pandas trả về số tháng (month number) từ từng phần tử trong PeriodIndex object. Tháng 1 = 1, Tháng 2 = 2, ..., Tháng 12 = 12.
Các bước thực hiện
1. Import thư viện
import pandas as pd
2. Tạo PeriodIndex
periodIndex = pd.PeriodIndex(
['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2021-07-15 02:55:15', '2022-06-25 09:40:55'],
freq="T"
)
3. Hiển thị tần suất
print("\nPeriodIndex frequency object...\n", periodIndex.freq)
4. Lấy số tháng
print("\nSố tháng từ PeriodIndex object...\n", periodIndex.month)
Ví dụ hoàn chỉnh
import pandas as pd
periodIndex = pd.PeriodIndex(
['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2021-07-15 02:55:15', '2022-06-25 09:40:55'],
freq="T"
)
print("PeriodIndex...\n", periodIndex)
print("\nPeriodIndex frequency object...\n", periodIndex.freq)
print("\nPeriodIndex frequency as string...\n", periodIndex.freqstr)
print("\nSố tháng từ PeriodIndex object...\n", periodIndex.month)
Kết quả đầu ra
PeriodIndex...
PeriodIndex(['2021-09-25 07:30', '2019-10-30 04:15', '2021-07-15 02:55', '2022-06-25 09:40'], dtype='period[T]')
PeriodIndex frequency object...
<Minute>
PeriodIndex frequency object as a string...
T
Số tháng từ PeriodIndex object...
Int64Index([9, 10, 7, 6], dtype='int64')
Giải thích: Các tháng tương ứng: 9 (tháng 9), 10 (tháng 10), 7 (tháng 7), 6 (tháng 6). Trả về Int64Index chứa các số nguyên.