Để lấy chỉ số (index locations) các giá trị trong DateTimeIndex nằm giữa khung giờ cụ thể, bao gồm start time, dùng phương thức DateTimeIndex.indexer_between_time() với include_start=True.
Các bước thực hiện
1. Import thư viện
import pandas as pd
2. Tạo DateTimeIndex
Tần suất 20 phút, 7 kỳ:
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='20T')
4. Lấy index locations giữa khung giờ (include_start=True)
print("\nIndex locations giữa khung giờ (include_start=True):\n", datetimeindex.indexer_between_time('03:10:50', '03:50:50', include_start=True))
Ví dụ hoàn chỉnh
import pandas as pd
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='20T')
print("DateTimeIndex:\n", datetimeindex)
print("\nTần suất:", datetimeindex.freq)
# Index tại thời điểm chính xác
print("\nIndex tại 03:10:50:\n", datetimeindex.indexer_at_time('2021-10-30 03:10:50'))
# Index giữa khung giờ, bao gồm start
print("\nIndex giữa 03:10:50 - 03:50:50 (include_start=True):\n", datetimeindex.indexer_between_time('03:10:50', '03:50:50', include_start=True))
Kết quả đầu ra
DateTimeIndex: DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 02:50:50+10:30', '2021-10-30 03:10:50+10:30', '2021-10-30 03:30:50+10:30', '2021-10-30 03:50:50+10:30', '2021-10-30 04:10:50+10:30', '2021-10-30 04:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='20T') Tần suất: <20 * Minutes> Index tại 03:10:50: [2] Index giữa 03:10:50 - 03:50:50 (include_start=True): [2 3 4]
Giải thích
| Index | Timestamp | |
|---|---|---|
| 0 | 02:30:50 | Không |
| 1 | 02:50:50 | Không |
| 2 | 03:10:50 | Có (start included) |
| 3 | 03:30:50 | Có |
| 4 | 03:50:50 | Có (end luôn included) |
| 5 | 04:10:50 | Không |
| 6 | 04:30:50 | Không |
Tham số include_start / include_end
indexer_between_time(start, end, include_start=True, include_end=True)
# Mặc định: include_start=False, include_end=True
Dùng include_start=True khi muốn bao gồm mốc bắt đầu (ví dụ: dữ liệu mở cửa thị trường).