Thuộc tính PeriodIndex.second trong Pandas trả về giây (second) từ từng phần tử trong PeriodIndex object. Yêu cầu tần suất phải là giây (freq='S') 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 giây
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="S"
)
3. Hiển thị PeriodIndex
print("PeriodIndex...\n", periodIndex)
4. Lấy giây
print("\nGiây từ PeriodIndex object...\n", periodIndex.second)
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="S"
)
print("PeriodIndex...\n", periodIndex)
print("\nPeriodIndex frequency object...\n", periodIndex.freq)
print("\nPeriodIndex frequency as string...\n", periodIndex.freqstr)
print("\nGiây từ PeriodIndex object...\n", periodIndex.second)
Kết quả đầu ra
PeriodIndex...
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'], dtype='period[S]')
PeriodIndex frequency object...
<Second>
PeriodIndex frequency object as a string...
S
Giây từ PeriodIndex object...
Int64Index([35, 45, 15, 55], dtype='int64')
Giải thích: Tần suất S (Second) cho phép truy xuất giây. Các giá trị: 35, 45, 15, 55 tương ứng với 4 timestamp đầu vào.
Lưu ý: Nếu PeriodIndex có tần suất thô hơn (ví dụ freq='T' phút), thuộc tính second sẽ báo lỗi AttributeError vì period không chứa thông tin giây.