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

Python Pandas: Tạo PeriodIndex và lấy thứ trong tuần

Thuộc tính PeriodIndex.dayofweek trong Pandas trả về thứ trong tuần (day of week) từ từng phần tử trong PeriodIndex object. Thứ 2 = 0, Thứ 3 = 1, ..., Chủ nhật = 6.

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 thứ trong tuần

print("\nThứ trong tuần từ PeriodIndex...\n", periodIndex.dayofweek)

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("\nThứ trong tuần từ PeriodIndex...\n", periodIndex.dayofweek)

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')
Thứ trong tuần từ PeriodIndex...
Int64Index([2, 2, 4, 2, 5, 6], dtype='int64')

Giải thích:

  • 25/7/2018 (Thứ 4) → 2
  • 30/10/2019 (Thứ 4) → 2
  • 20/11/2020 (Thứ 6) → 4
  • 15/9/2021 (Thứ 4) → 2
  • 12/3/2022 (Thứ 7) → 5
  • 18/6/2023 (Chủ nhật) → 6

Lưu ý: dayofweek và weekday là alias, cùng trả về 0-6 (Thứ 2 - CN).