Thuộc tính PeriodIndex.week trong Pandas trả về số tuần trong năm (week of year) từ từng phần tử trong PeriodIndex object. Giá trị từ 1-53.
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ị PeriodIndex
print("PeriodIndex...\n", periodIndex)
4. Lấy tuần
print("\nTuần từ PeriodIndex object...\n", periodIndex.week)
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("\nTuần từ PeriodIndex object...\n", periodIndex.week)
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
Tuần từ PeriodIndex object...
Int64Index([38, 44, 28, 25], dtype='int64')
Giải thích:
- 25/9/2021 → Tuần 38
- 30/10/2019 → Tuần 44
- 15/7/2021 → Tuần 28
- 25/6/2022 → Tuần 25
Lưu ý: Số tuần tuân theo tiêu chuẩn ISO (ISO week date) hoặc tiêu chuẩn US tùy phiên bản Pandas. Kiểm tra bằng pd.__version__.