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

Python Pandas - Trích xuất ngày trong tuần từ DateTimeIndex


Để lấy ngày trong tuần (0=Thứ 2, ..., 6=Chủ Nhật) từ DateTimeIndex, sử dụng thuộc tính DateTimeIndex.dayofweek.

Các bước thực hiện

1. Import thư viện

import pandas as pd

2. Tạo DateTimeIndex

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='3D')

3. Hiển thị tần suất

print("Tần suất...\n", datetimeindex.freq)

4. Lấy ngày trong tuần

print("\nNgày trong tuần (0=Thứ 2, 6=Chủ Nhật)...\n", datetimeindex.dayofweek)

Ví dụ hoàn chỉnh

import pandas as pd

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='3D')

print("DateTimeIndex...\n", datetimeindex)
print("Tần suất...\n", datetimeindex.freq)
print("\nNgày trong tuần...\n", datetimeindex.dayofweek)

Kết quả đầu ra

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+11:00', '2021-10-23 02:30:50+11:00',
               '2021-10-26 02:30:50+11:00', '2021-10-29 02:30:50+11:00',
               '2021-11-01 02:30:50+11:00', '2021-11-04 02:30:50+11:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='3D')
Tần suất...
<3 * Days>
Ngày trong tuần...
Int64Index([2, 5, 1, 4, 0, 3], dtype='int64')

Giải thích: 20/10/2021 là Thứ 4 (2), 23/10 là Thứ 7 (5), 26/10 là Thứ 3 (1), 29/10 là Thứ 6 (4), 1/11 là Thứ 2 (0), 4/11 là Thứ 5 (3).