Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas: Lấy phút từ PeriodIndex object

Thuộc tính PeriodIndex.minute trong Pandas trả về phút (minute) từ từng phần tử trong PeriodIndex object. Yêu cầu tần suất phải là phút (freq='T' hoặc 'min') hoặc cao hơn.

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: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ị PeriodIndex

print("PeriodIndex...\n", periodIndex)

4. Lấy phút

print("\nPhút từ PeriodIndex object...\n", periodIndex.minute)

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("\nPhút từ PeriodIndex object...\n", periodIndex.minute)

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
Phút từ PeriodIndex object...
Int64Index([30, 15, 55, 40], dtype='int64')

Giải thích: Tần suất T (Minute) cho phép truy xuất phút. Các giá trị: 30, 15, 55, 40. Lưu ý: giây (35, 45, 15, 55) bị cắt bỏ do tần suất chỉ đến phút.