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

Python Pandas - Lấy chỉ số index giá trị giữa khung giờ bao gồm start time

Để 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

Trong khoảng [03:10:50, 03:50:50]?
IndexTimestamp
002:30:50Không
102:50:50Không
203:10:50Có (start included)
303:30:50Có
403:50:50Có (end luôn included)
504:10:50Không
604:30:50Khô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).