Thuộc tính PeriodIndex.dayofyear trong Pandas trả về thứ tự ngày trong năm (day of year, 1-366) từ từng phần tử trong PeriodIndex object.
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 ngày
periodIndex = pd.PeriodIndex(
['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'],
freq="D"
)
3. Hiển thị PeriodIndex
print("PeriodIndex...\n", periodIndex)
4. Lấy ngày trong năm
print("\nNgày trong năm từ PeriodIndex...\n", periodIndex.dayofyear)
Ví dụ hoàn chỉnh
import pandas as pd
periodIndex = pd.PeriodIndex(
['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'],
freq="D"
)
print("PeriodIndex...\n", periodIndex)
print("\nPeriodIndex frequency...\n", periodIndex.freq)
print("\nNgày trong tháng từ PeriodIndex...\n", periodIndex.day)
print("\nNgày trong năm từ PeriodIndex...\n", periodIndex.dayofyear)
Kết quả đầu ra
PeriodIndex...
PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'], dtype='period[D]')
PeriodIndex frequency...
<Day>
Ngày trong tháng từ PeriodIndex...
Int64Index([25, 30, 20, 15, 12, 18], dtype='int64')
Ngày trong năm từ PeriodIndex...
Int64Index([206, 303, 325, 258, 71, 169], dtype='int64')
Giải thích:
day: Ngày trong tháng (1-31)dayofyear: Ngày trong năm (1-366)
Chi tiết:
- 25/7/2018 → ngày 206 (năm thường)
- 30/10/2019 → ngày 303
- 20/11/2020 → ngày 325 (năm nhuận, sau 29/2)
- 15/9/2021 → ngày 258
- 12/3/2022 → ngày 71
- 18/6/2023 → ngày 169