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

Python Pandas: Lấy thứ trong tuần từ PeriodIndex object

Thuộc tính PeriodIndex.weekday 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 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 thứ trong tuần

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

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

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

Giải thích:

  • 25/9/2021 (Thứ 7) → 5
  • 30/10/2019 (Thứ 3) → 2
  • 15/7/2021 (Thứ 4) → 3
  • 25/6/2022 (Thứ 7) → 5

Lưu ý: weekday và dayofweek là alias của nhau, cả hai đều trả về 0-6 (Thứ 2 - CN). week trả về số tuần trong năm (1-53).