Thuộc tính PeriodIndex.hour trong Pandas trả về giờ (hour) từ từng phần tử trong PeriodIndex object. Yêu cầu tần suất phải là giờ (freq='H') hoặc cao hơn (phút, giây).
Các bước thực hiện
1. Import thư viện
import pandas as pd
2. Tạo PeriodIndex tần suất phút
periodIndex = pd.PeriodIndex(
['2021-09-25 07:50:35', '2019-10-30 04:35:45',
'2021-07-15 02:25:15', '2022-06-25 09:20:55'],
freq="T"
)
3. Hiển thị PeriodIndex
print("PeriodIndex...\n", periodIndex)
4. Lấy giờ
print("\nGiờ từ PeriodIndex object...\n", periodIndex.hour)
Ví dụ hoàn chỉnh
import pandas as pd
periodIndex = pd.PeriodIndex(
['2021-09-25 07:50:35', '2019-10-30 04:35:45',
'2021-07-15 02:25:15', '2022-06-25 09:20:55'],
freq="T"
)
print("PeriodIndex...\n", periodIndex)
print("\nPeriodIndex frequency object...\n", periodIndex.freq)
print("\nPeriodIndex frequency as string...\n", periodIndex.freqstr)
print("\nGiờ từ PeriodIndex object...\n", periodIndex.hour)
Kết quả đầu ra
PeriodIndex...
PeriodIndex(['2021-09-25 07:50', '2019-10-30 04:35', '2021-07-15 02:25', '2022-06-25 09:20'], dtype='period[T]')
PeriodIndex frequency object...
<Minute>
PeriodIndex frequency object as a string...
T
Giờ từ PeriodIndex object...
Int64Index([7, 4, 2, 9], dtype='int64')
Giải thích: Tần suất T (Minute) chứa thông tin giờ. Các giá trị giờ: 7, 4, 2, 9 (định dạng 24h).